package com.example.show_auto.ui.pages

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.withStyle
import androidx.compose.material3.LocalTextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.show_auto.data.Chef
import com.example.show_auto.data.Equip
import com.example.show_auto.data.GameData
import com.example.show_auto.data.PersonalData
import com.example.show_auto.data.Quest
import com.example.show_auto.data.Recipe
import com.example.show_auto.data.Skill
import com.example.show_auto.data.SettingsStorage
import com.example.show_auto.data.PersonalDataManager
import com.example.show_auto.data.UltimateDataStorage
import com.example.show_auto.ui.pages.UltimateSkillsState
import com.example.show_auto.utils.ChefSkillCalculator
import com.example.show_auto.utils.ChefInteractionCalculator
import com.example.show_auto.utils.EquipRecommendationCalculator
import com.example.show_auto.utils.OneClickQueryCalculator
import com.example.show_auto.utils.RecipeRankCalculator
import com.example.show_auto.viewmodel.MainViewModel
import com.example.show_auto.ui.utils.DeviceCompatibility
import com.example.show_auto.ui.theme.getChefBoxCompatibleCardColors
import com.example.show_auto.ui.theme.getDarkGreyBackgroundColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults

/**
 * 修炼菜谱查询页面 - 完全按照web项目计算器页面逻辑实现
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RecipeCalculatorPage(
    viewModel: MainViewModel,
    onMenuClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val gameData by viewModel.gameData.collectAsState()
    val personalData by viewModel.personalData.collectAsState()
    val uiState by viewModel.uiState.collectAsState()
    
    // 设置存储和个人技法数据
    val context = LocalContext.current
    val ultimateStorage = remember { UltimateDataStorage(context) }
    val settingsStorage = remember { SettingsStorage(context) }
    val personalDataManager = remember { PersonalDataManager(context) }
    var ultimateSkills by remember { mutableStateOf(UltimateSkillsState()) }
    var recipeLimits by remember { mutableStateOf(com.example.show_auto.ui.pages.RecipeLimitsState()) }

    // 全局的光环厨师设置状态
    var globalEnabledAuraChefs by remember { mutableStateOf(settingsStorage.getSelectedAuraChefs()) }
    
    // 监听gameData和personalData变化，重新判断和保存光环厨师设置
    LaunchedEffect(gameData, personalData) {
        val currentGameData = gameData
        val currentPersonalData = personalData
        
        if (currentGameData != null && currentPersonalData != null) {
            println("DEBUG: 进入查询厨师修炼页面，重新判断光环厨师状态")
            
            // 重新识别当前游戏数据中的所有光环厨师
            val allAuraChefs = currentGameData.chefs.filter { chef ->
                isAuraChef(chef, currentGameData.skills)
            }
            val allAuraChefNames = allAuraChefs.map { it.name }.toSet()
            println("DEBUG: 识别到的光环厨师总数: ${allAuraChefNames.size}")
            println("DEBUG: 光环厨师列表: ${allAuraChefNames.joinToString(", ")}")
            
            // 保存所有光环厨师名称到设置存储
            settingsStorage.saveAllAuraChefNames(allAuraChefNames)
            
            // 根据当前用户的拥有和修炼状态，确定应该启用的光环厨师
            val shouldBeEnabledAuraChefs = currentGameData.chefs.filter { chef ->
                chef.got && chef.ult && isAuraChef(chef, currentGameData.skills)
            }.map { it.name }.toSet()
            println("DEBUG: 当前用户应该启用的光环厨师: ${shouldBeEnabledAuraChefs.joinToString(", ")}")
            
            // 获取当前保存的光环厨师选择
            val currentSelection = settingsStorage.getSelectedAuraChefs()
            println("DEBUG: 当前保存的光环厨师选择: ${currentSelection.joinToString(", ")}")
            
            // 每次进入页面都重新判断和保存，确保与当前用户状态同步
            if (currentSelection != shouldBeEnabledAuraChefs) {
                println("DEBUG: 光环厨师状态发生变化，重新保存设置")
                // 自动勾选已拥有且已修炼的光环厨师
                settingsStorage.saveSelectedAuraChefs(shouldBeEnabledAuraChefs)
                globalEnabledAuraChefs = shouldBeEnabledAuraChefs
                
                // 同时保存到用户个人数据
                personalDataManager.saveUserAuraChefs(shouldBeEnabledAuraChefs)
            } else {
                println("DEBUG: 光环厨师状态未变化，使用保存的设置")
                // 状态没变化，使用保存的设置
                globalEnabledAuraChefs = currentSelection
            }
        } else if (currentGameData != null) {
            // 当gameData更新但没有personalData时，只重新读取设置
            globalEnabledAuraChefs = settingsStorage.getSelectedAuraChefs()
        }
    }
    
    // 加载个人技法数据
    LaunchedEffect(Unit) {
        ultimateStorage.loadUltimateData()?.let { (skills, limits, _) ->
            ultimateSkills = skills
            recipeLimits = limits
        }
    }

    // 选中的厨师状态（最多6个）
    var selectedChefs by remember { mutableStateOf<List<Chef>>(emptyList()) }

    // 选中的菜谱状态（最多6个）
    var selectedRecipes by remember { mutableStateOf<List<Recipe>>(emptyList()) }
    
    // 菜谱实际分配份数（对应selectedRecipes，用于一键查询）
    var recipePortions by remember { mutableStateOf<List<Int>>(emptyList()) }
    
    // 计算结果状态
    var totalScore by remember { mutableStateOf(0) }
    var totalTime by remember { mutableStateOf(0) }
    var efficiency by remember { mutableStateOf(0) }
    var goldPerHour by remember { mutableStateOf(0) }
    
    // 厨师选择对话框状态
    var showChefDialog by remember { mutableStateOf(false) }
    var selectedSlotIndex by remember { mutableStateOf(-1) }

    // 厨具选择对话框状态
    var showEquipDialog by remember { mutableStateOf(false) }
    var selectedEquipSlotIndex by remember { mutableStateOf(-1) }

    // 菜谱选择对话框状态
    var showRecipeDialog by remember { mutableStateOf(false) }
    var selectedRecipeSlotIndex by remember { mutableStateOf(-1) }

    // 设置对话框状态
    var showSettingsDialog by remember { mutableStateOf(false) }
    
    // 使用说明弹窗状态
    var showUsageDialog by remember { mutableStateOf(false) }

    // 查询厨师相关状态
    var selectedQueryChef by remember { mutableStateOf<Chef?>(null) }

    // 下拉框相关状态
    var searchQuery by remember { mutableStateOf("") }
    var isDropdownExpanded by remember { mutableStateOf(false) }
    val interactionSource = remember { MutableInteractionSource() }
    
    // 手动选择菜谱份数自动计算函数
    fun calculateManualRecipePortions() {
        if (selectedQueryChef == null || gameData == null) {
            recipePortions = emptyList()
            return
        }
        
        // 获取厨师的修炼任务
        val chef = selectedQueryChef!!
        val currentGameData = gameData ?: return
        val quest = if (chef.ultimateGoal.isNotEmpty()) {
            currentGameData.quests.find { it.questId == chef.ultimateGoal.first() }
        } else null
        
        if (quest == null || quest.conditions.isEmpty()) {
            recipePortions = emptyList()
            return
        }
        
        val condition = quest.conditions.first()
        val totalRequiredPortions = condition.num
        
        // 计算每个菜谱的份数
        val portions = MutableList(selectedRecipes.size) { 0 }
        var remainingPortions = totalRequiredPortions
        
        for (i in selectedRecipes.indices) {
            val recipe = selectedRecipes[i]
            if (recipe.name.isNotEmpty()) {
                // 计算单个菜谱的最大份数
                val basePortions = when (recipe.rarity) {
                    1 -> 40
                    2 -> 30
                    3 -> 25
                    4 -> 20
                    5 -> 15
                    else -> 0
                }
                
                val limitBonus = when (recipe.rarity) {
                    1 -> recipeLimits.star1
                    2 -> recipeLimits.star2
                    3 -> recipeLimits.star3
                    4 -> recipeLimits.star4
                    5 -> recipeLimits.star5
                    else -> 0
                }
                
                val maxPortions = basePortions + limitBonus
                val actualPortions = minOf(maxPortions, remainingPortions)
                portions[i] = maxOf(actualPortions, 0)
                remainingPortions -= actualPortions
                
                if (remainingPortions <= 0) break
            }
        }
        
        recipePortions = portions
    }
    
    // 监听输入框点击事件
    LaunchedEffect(interactionSource) {
        interactionSource.interactions.collect { interaction ->
            when (interaction) {
                is PressInteraction.Press -> {
                    if (selectedQueryChef == null) {
                        isDropdownExpanded = true
                    }
                }
            }
        }
    }

    // 选中的厨具状态（最多3个）
    var selectedEquips by remember { mutableStateOf<List<Equip>>(emptyList()) }

    // 使用全局的光环厨师设置状态

    // 计算厨师间技法影响
    val chefInteractions = remember(selectedChefs, gameData?.skills, globalEnabledAuraChefs) {
        ChefInteractionCalculator.calculateChefInteractions(
            selectedChefs,
            gameData?.skills ?: emptyList(),
            globalEnabledAuraChefs
        )
    }

    // 只查已拥有开关状态 - 从存储中加载初始值
    var onlyShowOwnedChefs by remember { mutableStateOf(settingsStorage.getFilterOwnedChefs()) }
    var onlyShowOwnedRecipes by remember { mutableStateOf(settingsStorage.getFilterOwnedRecipes()) }

    // 光环厨师筛选状态 - 从存储中加载初始值
    var onlyShowAuraChefs by remember { mutableStateOf(settingsStorage.getFilterAuraChefs()) }

    // 已修炼厨师筛选状态 - 从存储中加载初始值
    var onlyShowUltimateChefs by remember { mutableStateOf(settingsStorage.getFilterUltimateChefs()) }
    
    // 未修炼厨师筛选状态 - 从存储中加载初始值
    var onlyShowNonUltimateChefs by remember { mutableStateOf(settingsStorage.getFilterNonUltimateChefs()) }

    // 厨具筛选状态 - 从存储中加载初始值
    var equipFilterSkill by remember { mutableStateOf(settingsStorage.getEquipFilterSkill()) }
    var equipFilterRarity1 by remember { mutableStateOf(settingsStorage.getEquipFilterRarity1()) }
    var equipFilterRarity2 by remember { mutableStateOf(settingsStorage.getEquipFilterRarity2()) }
    var equipFilterRarity3 by remember { mutableStateOf(settingsStorage.getEquipFilterRarity3()) }

    // 任务类型筛选按钮状态
    var showCollisionTaskChefs by remember { mutableStateOf(false) }
    var showTimeTaskChefs by remember { mutableStateOf(false) }
    var showPortionTaskChefs by remember { mutableStateOf(false) }

    // 查询未拥有厨师筛选状态
    var showUnownedChefs by remember { mutableStateOf(false) }



    // 辅助函数：获取厨师第三个修炼任务的描述
    fun getThirdUltimateTaskDescription(chef: Chef, quests: List<Quest>): String {
        if (chef.ultimateGoal.size < 3) return ""
        val thirdTaskId = chef.ultimateGoal[2]
        return quests.find { quest -> quest.questId == thirdTaskId }?.goal ?: ""
    }

    // 辅助函数：获取厨师所有修炼任务的描述
    fun getAllUltimateTaskDescriptions(chef: Chef, quests: List<Quest>): String {
        if (chef.ultimateGoal.isEmpty()) return ""
        val descriptions = chef.ultimateGoal.mapNotNull { taskId ->
            quests.find { quest -> quest.questId == taskId }?.goal
        }
        return descriptions.joinToString(" | ")
    }

    // 辅助函数：获取厨师所有修炼任务的描述列表
    fun getAllUltimateTaskDescriptionsList(chef: Chef, quests: List<Quest>): List<String> {
        if (chef.ultimateGoal.isEmpty()) return emptyList()
        return chef.ultimateGoal.mapNotNull { taskId ->
            quests.find { quest -> quest.questId == taskId }?.goal
        }
    }

    // 根据搜索条件过滤厨师 - 支持查询已有未修炼厨师或未拥有厨师
    val filteredChefs = remember(gameData, searchQuery, selectedQueryChef, showCollisionTaskChefs, showTimeTaskChefs, showPortionTaskChefs, showUnownedChefs) {
        if (selectedQueryChef != null) {
            emptyList() // 如果已选择厨师，不显示列表
        } else {
            gameData?.chefs?.filter { chef ->
                // 基本筛选条件
                val basicCondition = if (showUnownedChefs) {
                    // 查询未拥有厨师模式
                    !chef.got && // 未拥有的厨师
                        !chef.name.contains("雍正") && // 排除雍正
                        (searchQuery.isEmpty() || chef.name.contains(searchQuery, ignoreCase = true))
                } else {
                    // 查询已有未修炼厨师模式（原逻辑）
                    chef.got && // 已拥有的厨师
                    !chef.ult && // 未修炼的厨师
                    !chef.name.contains("雍正") && // 排除雍正（永远不能修炼）
                    (searchQuery.isEmpty() || chef.name.contains(searchQuery, ignoreCase = true))
                }
                
                if (!basicCondition) return@filter false
                
                // 组合查询逻辑：支持四个按钮的组合筛选
                val hasTaskTypeFilter = showCollisionTaskChefs || showTimeTaskChefs || showPortionTaskChefs
                
                // 如果没有选择任何筛选条件，显示所有符合基本条件的厨师
                if (!showUnownedChefs && !hasTaskTypeFilter) {
                    return@filter true
                }
                
                // 检查拥有状态筛选
                val matchesOwnershipFilter = if (showUnownedChefs) {
                    !chef.got // 查询未拥有：必须是未拥有的厨师
                } else {
                    chef.got && !chef.ult // 默认：已拥有但未修炼的厨师
                }
                
                // 检查任务类型筛选
                val matchesTaskTypeFilter = if (hasTaskTypeFilter) {
                    val quests = gameData?.quests ?: emptyList()
                    val thirdTaskDescription = getThirdUltimateTaskDescription(chef, quests)
                    
                val matchesCollisionTask = showCollisionTaskChefs && thirdTaskDescription.contains("特殊客人")
                val matchesTimeTask = showTimeTaskChefs && thirdTaskDescription.contains("累计开业")
                val matchesPortionTask = showPortionTaskChefs && thirdTaskDescription.contains("累计制作")
                
                    // 任务类型之间是OR关系（符合任意一个即可）
                matchesCollisionTask || matchesTimeTask || matchesPortionTask
                } else {
                    true // 如果没有任务类型筛选，则通过
                }
                
                // 组合查询：必须同时满足拥有状态筛选 AND 任务类型筛选
                matchesOwnershipFilter && matchesTaskTypeFilter
            }?.sortedWith { chef1, chef2 ->
                // 按厨师ID降序排序（ID越大越靠前）
                val id1 = chef1.chefId.toIntOrNull() ?: 0
                val id2 = chef2.chefId.toIntOrNull() ?: 0
                id2.compareTo(id1)
            } ?: emptyList()
        }
    }

    // 检查是否有对应任务类型的厨师（包括已修炼的）- 用于显示提示信息
    val hasTaskTypeChefs = remember(gameData, showCollisionTaskChefs, showTimeTaskChefs, showPortionTaskChefs) {
        if (!showCollisionTaskChefs && !showTimeTaskChefs && !showPortionTaskChefs) {
            true // 没有筛选时不需要检查
        } else {
            gameData?.chefs?.any { chef ->
                val basicCondition = chef.got && !chef.name.contains("雍正")
                if (!basicCondition) return@any false
                
                val quests = gameData?.quests ?: emptyList()
                val thirdTaskDescription = getThirdUltimateTaskDescription(chef, quests)
                
                val matchesCollisionTask = showCollisionTaskChefs && thirdTaskDescription.contains("特殊客人")
                val matchesTimeTask = showTimeTaskChefs && thirdTaskDescription.contains("累计开业")
                val matchesPortionTask = showPortionTaskChefs && thirdTaskDescription.contains("累计制作")
                
                matchesCollisionTask || matchesTimeTask || matchesPortionTask
            } ?: false
        }
    }

    // 获取当前选中的任务类型名称
    val currentTaskTypeName = remember(showCollisionTaskChefs, showTimeTaskChefs, showPortionTaskChefs) {
        when {
            showCollisionTaskChefs && !showTimeTaskChefs && !showPortionTaskChefs -> "贵客任务"
            !showCollisionTaskChefs && showTimeTaskChefs && !showPortionTaskChefs -> "时长任务"
            !showCollisionTaskChefs && !showTimeTaskChefs && showPortionTaskChefs -> "份数任务"
            else -> "选中类型任务"
        }
    }

    // 厨师点击处理
    val onChefClick: (Int) -> Unit = { index ->
        selectedSlotIndex = index
        showChefDialog = true
    }

    // 厨具点击处理
    val onEquipClick: (Int) -> Unit = { index ->
        selectedEquipSlotIndex = index
        showEquipDialog = true
    }

    // 菜谱点击处理
    val onRecipeClick: (Int) -> Unit = { index ->
        selectedRecipeSlotIndex = index
        showRecipeDialog = true
    }

    DeviceCompatibility.AdaptiveContainer(
        modifier = modifier.fillMaxSize()
    ) {
        Column(
            modifier = Modifier.fillMaxSize()
    ) {
        // 顶部应用栏
        TopAppBar(
            title = {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        text = "查询厨师修炼",
                        fontWeight = FontWeight.Medium
                    )
                    IconButton(
                        onClick = { showUsageDialog = true },
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = "使用说明",
                            modifier = Modifier.size(20.dp)
                        )
                    }
                }
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(
                        imageVector = Icons.Default.Menu,
                        contentDescription = "菜单"
                    )
                }
            },
            actions = {
                IconButton(onClick = { showSettingsDialog = true }) {
                    Icon(
                        imageVector = Icons.Default.Settings,
                        contentDescription = "设置"
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )
        
        if (!uiState.isCodeValid || gameData == null) {
            // 未验证状态
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Lock,
                        contentDescription = "需要验证",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.size(48.dp)
                    )
                    Text(
                        text = "请先在个人数据页面导入数据",
                        fontSize = 16.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = TextAlign.Center
                    )
                }
            }
        } else {
            // 主要内容 - 完全按照web项目布局
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                // 查询厨师区域
                    Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(
                            horizontal = DeviceCompatibility.getAdaptiveSpacing(16.dp),
                            vertical = DeviceCompatibility.getAdaptiveSpacing(4.dp)
                        ),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.Top
                ) {
                    // 厨师选择输入框（自定义实现）
                    BoxWithConstraints(
                        modifier = Modifier
                            .weight(1f)
                            .padding(3.dp)
                    ) {
                        val maxWidth = maxWidth
                        OutlinedTextField(
                            value = selectedQueryChef?.name ?: searchQuery,
                            onValueChange = { query ->
                                searchQuery = query
                                selectedQueryChef = null
                                isDropdownExpanded = true // 输入时始终展开下拉列表
                            },
                            label = { Text("选择未修炼厨师", fontSize = 11.sp) },
                            placeholder = { 
                                Text(
                                    "输入厨师名称搜索", 
                                    fontSize = 10.sp, 
                                    lineHeight = 16.sp,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                ) 
                            },
                            leadingIcon = {
                                Icon(
                                    imageVector = Icons.Default.Person,
                                    contentDescription = "厨师",
                                    modifier = Modifier.size(20.dp)
                                )
                            },
                            trailingIcon = {
                                Row(
                                    modifier = Modifier
                                        .width(48.dp) // 固定宽度，确保收起按钮位置不变
                                        .offset(x = (-8).dp), // 整体向左移动8dp
                                    horizontalArrangement = Arrangement.End,
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    // 清除按钮
                                    if (selectedQueryChef != null || searchQuery.isNotEmpty()) {
                                        IconButton(
                                            onClick = {
                                                selectedQueryChef = null
                                                searchQuery = ""
                                                isDropdownExpanded = false
                                            },
                                            modifier = Modifier.size(20.dp)
                                        ) {
                                            Icon(
                                                imageVector = Icons.Default.Clear,
                                                contentDescription = "清除",
                                                modifier = Modifier.size(14.dp)
                                            )
                                        }
                                    }

                                    // 展开/收起按钮 - 始终在最右侧
                                    IconButton(
                                        onClick = {
                                            if (selectedQueryChef == null) {
                                                isDropdownExpanded = !isDropdownExpanded
                                            }
                                        },
                                        modifier = Modifier.size(24.dp)
                                    ) {
                                        Icon(
                                            imageVector = if (isDropdownExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                            contentDescription = if (isDropdownExpanded) "收起" else "展开",
                                            modifier = Modifier.size(18.dp)
                                        )
                                    }
                                }
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(55.dp),
                            singleLine = true,
                            textStyle = androidx.compose.ui.text.TextStyle(fontSize = 12.sp),
                            colors = DeviceCompatibility.getAdaptiveTextFieldColors(),
                            interactionSource = interactionSource
                        )

                        // 下拉列表将在BoxWithConstraints外部显示

                    }
                    
                    // 一键查询按钮
                        Button(
                            onClick = {
                            // 执行一键查询逻辑
                            if (selectedQueryChef == null) {
                                return@Button
                            }
                            
                            val chef = selectedQueryChef!!
                            
                            if (gameData == null) {
                                return@Button
                            }
                            
                            val result = OneClickQueryCalculator.executeOneClickQuery(
                                targetChef = chef,
                                gameData = gameData!!,
                                allChefs = gameData!!.chefs,
                                allRecipes = gameData!!.recipes,
                                allEquips = gameData!!.equips,
                                skills = gameData!!.skills,
                                ultimateSkills = ultimateSkills,
                                recipeLimits = recipeLimits,
                                settingsStorage = settingsStorage
                            )
                            
                            
                            if (result.success) {
                                
                                // 更新选择框内容
                                selectedChefs = result.selectedChefs.toMutableList()
                                selectedEquips = result.selectedEquips.toMutableList()
                                selectedRecipes = result.selectedRecipes.toMutableList()
                                recipePortions = result.recipePortions.toMutableList()
                                

                            }
                        },
                        modifier = Modifier
                            .height(50.dp)
                            .offset(y = 9.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary
                        ),
                        shape = RoundedCornerShape(8.dp),
                        contentPadding = PaddingValues(horizontal = 16.dp, vertical = 0.dp)
                    ) {
                        Text(
                            "一键查询",
                            fontSize = 12.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }
                }




                // 下拉框覆盖层 - 显示在Row外部，确保在最顶层
                if (isDropdownExpanded && selectedQueryChef == null) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 19.dp) // 与搜索框对齐
                    ) {
                        // 任务类型筛选按钮行
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                                .padding(vertical = 4.dp),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                            // 碰瓷任务厨师按钮
                            OutlinedButton(
                                onClick = {
                                    showCollisionTaskChefs = !showCollisionTaskChefs
                                },
                            modifier = Modifier
                                .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showCollisionTaskChefs) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showCollisionTaskChefs) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "贵客任务",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }

                            // 时长任务厨师按钮
                            OutlinedButton(
                                onClick = {
                                    showTimeTaskChefs = !showTimeTaskChefs
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showTimeTaskChefs) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showTimeTaskChefs) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "时长任务",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }

                            // 份数任务厨师按钮
                            OutlinedButton(
                            onClick = {
                                    showPortionTaskChefs = !showPortionTaskChefs
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showPortionTaskChefs) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showPortionTaskChefs) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "份数任务",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }

                            // 查询未拥有厨师按钮
                            OutlinedButton(
                                onClick = {
                                    showUnownedChefs = !showUnownedChefs
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showUnownedChefs) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showUnownedChefs) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "查询未拥有",
                                    fontSize = 9.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }
                        }

                        // 厨师列表卡片
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(max = 400.dp),
                            elevation = CardDefaults.cardElevation(defaultElevation = 16.dp)
                        ) {
                        if (filteredChefs.isNotEmpty()) {
                            LazyColumn {
                                items(filteredChefs) { chef ->
                                    Column(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .clickable {
                                                selectedQueryChef = chef
                                                searchQuery = ""
                                                isDropdownExpanded = false
                                                // 选择厨师后重新计算菜谱份数
                                                calculateManualRecipePortions()
                                            }
                                            .padding(start = 16.dp, top = 16.dp, bottom = 16.dp, end = 8.dp) // 减少右侧padding，给任务描述更多空间
                                    ) {
                                        // 第一行：厨师名称、星级和任务描述
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            verticalAlignment = Alignment.Top
                                        ) {
                                            // 左侧：厨师名称和星级（固定宽度以对齐任务描述）
                                            Row(
                                                modifier = Modifier.width(120.dp), // 设置固定宽度
                                                verticalAlignment = Alignment.CenterVertically
                                            ) {
                                                // 厨师名称
                                                Text(
                                                    text = chef.name,
                                                    fontSize = 12.sp,
                                                    fontWeight = FontWeight.Medium
                                                )
                                                Spacer(modifier = Modifier.width(4.dp))
                                                // 星级显示
                                                repeat(chef.rarity) {
                                                    Icon(
                                                        imageVector = Icons.Default.Star,
                                                        contentDescription = null,
                                                        tint = MaterialTheme.colorScheme.primary,
                                                        modifier = Modifier.size(12.dp)
                                                    )
                                                }
                                            }
                                            
                                            // 右侧：修炼任务描述（换行显示）
                                            val taskDescriptionsList = getAllUltimateTaskDescriptionsList(chef, gameData?.quests ?: emptyList())
                                            if (taskDescriptionsList.isNotEmpty()) {
                                                Column(
                                                    modifier = Modifier.weight(1f)
                                                ) {
                                                    taskDescriptionsList.forEach { description ->
                                                        Text(
                                                            text = description,
                                                            fontSize = 10.sp,
                                                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                            lineHeight = 12.sp
                                                        )
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    // 添加横隔线（除了最后一个项目）
                                    if (chef != filteredChefs.last()) {
                                        HorizontalDivider()
                                    }
                                }
                            }
                        } else {
                            // 显示提示信息
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(24.dp),
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Info,
                                    contentDescription = "提示",
                                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                    modifier = Modifier.size(32.dp)
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                
                                // 根据不同情况显示不同的提示信息
                                val message = when {
                                    // 查询未拥有厨师模式的提示信息
                                    showUnownedChefs -> {
                                        if (searchQuery.isNotEmpty()) {
                                            "未找到匹配的未拥有厨师"
                                        } else {
                                            "暂无未拥有厨师"
                                        }
                                    }
                                    // 如果有任务类型筛选且有对应的厨师，说明厨师全部已修炼
                                    (showCollisionTaskChefs || showTimeTaskChefs || showPortionTaskChefs) && hasTaskTypeChefs -> {
                                        "${currentTaskTypeName}厨师全部已修炼"
                                    }
                                    // 如果有任务类型筛选但没有对应的厨师，说明没有这类任务的厨师
                                    (showCollisionTaskChefs || showTimeTaskChefs || showPortionTaskChefs) && !hasTaskTypeChefs -> {
                                        "暂无${currentTaskTypeName}厨师"
                                    }
                                    // 如果有搜索条件，说明没有匹配的厨师
                                    searchQuery.isNotEmpty() -> {
                                        "未找到匹配的厨师"
                                    }
                                    // 默认情况：没有未修炼的厨师
                                    else -> {
                                        "暂无未修炼厨师"
                                    }
                                }
                                
                                Text(
                                    text = message,
                                    fontSize = 14.sp,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    textAlign = TextAlign.Center
                                )
                                
                                // 如果是搜索结果为空，提供清空搜索的选项
                                if (searchQuery.isNotEmpty()) {
                                    Spacer(modifier = Modifier.height(8.dp))
                                    TextButton(
                                        onClick = {
                                            searchQuery = ""
                                        }
                                    ) {
                                        Text("清空搜索")
                                    }
                                }
                            }
                        }
                        } // 结束Card
                    } // 结束Column
                }

                // 清空全部按钮 - 放在下拉框之后，同样进行偏移
                OutlinedButton(
                    onClick = {
                        // 清空所有选择的数据
                        selectedChefs = emptyList()
                        selectedEquips = emptyList()
                        selectedRecipes = emptyList()
                        recipePortions = emptyList()
                        selectedQueryChef = null
                        searchQuery = ""
                        isDropdownExpanded = false
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp)
                        .padding(top = if (isDropdownExpanded && selectedQueryChef == null) 440.dp else 4.dp) // 下拉框展开时偏移到下拉框下方（增加按钮高度）
                        .height(32.dp),
                    colors = ButtonDefaults.outlinedButtonColors(
                        containerColor = Color.White,
                        contentColor = Color.Black
                    ),
                    shape = RoundedCornerShape(8.dp),
                    border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline)
                ) {
                    Text(
                        "清空全部",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium
                    )
                }

                // 主要内容区域
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(DeviceCompatibility.getAdaptiveSpacing(16.dp))
                        .padding(top = if (isDropdownExpanded && selectedQueryChef == null) 800.dp else 0.dp) // 只有下拉框展开时才偏移800dp
                        .verticalScroll(rememberScrollState()),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 自选页面内容（完全按照web项目自选页面结构）
                    CustomSelectionPage(
                        selectedChefs = selectedChefs,
                        selectedEquips = selectedEquips,
                        selectedRecipes = selectedRecipes,
                        recipePortions = recipePortions,
                        skills = gameData?.skills ?: emptyList(),
                        ultimateSkills = ultimateSkills,
                        recipeLimits = recipeLimits,
                        allChefs = gameData?.chefs ?: emptyList(),
                        allRecipes = gameData?.recipes ?: emptyList(),
                        totalScore = totalScore,
                        totalTime = totalTime,
                        efficiency = efficiency,
                        goldPerHour = goldPerHour,
                        enabledAuraChefs = globalEnabledAuraChefs,
                        gameData = gameData,
                        onChefClick = onChefClick,
                        onEquipClick = onEquipClick,
                        onRecipeClick = onRecipeClick
                    )
                }
            }
        }
    }

    // 厨师选择对话框
    if (showChefDialog) {
        ChefSelectionDialog(
            chefs = gameData?.chefs ?: emptyList(),
            selectedChefs = selectedChefs,
            skills = gameData?.skills ?: emptyList(),
            ultimateSkills = ultimateSkills,
            onlyShowOwned = onlyShowOwnedChefs,
            onOnlyShowOwnedChange = { 
                onlyShowOwnedChefs = it
                settingsStorage.saveFilterOwnedChefs(it)
            },
            onlyShowAuraChefs = onlyShowAuraChefs,
            onOnlyShowAuraChefsChange = {
                onlyShowAuraChefs = it
                settingsStorage.saveFilterAuraChefs(it)
            },
            onlyShowUltimateChefs = onlyShowUltimateChefs,
            onOnlyShowUltimateChefsChange = {
                onlyShowUltimateChefs = it
                settingsStorage.saveFilterUltimateChefs(it)
            },
            onlyShowNonUltimateChefs = onlyShowNonUltimateChefs,
            onOnlyShowNonUltimateChefsChange = {
                onlyShowNonUltimateChefs = it
                settingsStorage.saveFilterNonUltimateChefs(it)
            },
            onChefSelected = { chef ->
                if (selectedSlotIndex >= 0 && selectedSlotIndex < 3) {
                    val newList = selectedChefs.toMutableList()
                    // 确保列表有足够的元素，但不添加空厨师
                    while (newList.size <= selectedSlotIndex) {
                        newList.add(Chef(name = "")) // 添加占位厨师，名称为空
                    }
                    newList[selectedSlotIndex] = chef
                    selectedChefs = newList
                }
                showChefDialog = false
            },
            onClearCurrentChef = {
                // 只清空当前选择框的厨师
                if (selectedSlotIndex >= 0 && selectedSlotIndex < selectedChefs.size) {
                    val newList = selectedChefs.toMutableList()
                    newList[selectedSlotIndex] = Chef(name = "") // 设置为空厨师
                    selectedChefs = newList
                }
            },
            onDismiss = { showChefDialog = false }
        )
    }

    // 厨具选择对话框
    if (showEquipDialog) {
        EquipSelectionDialog(
            equips = gameData?.equips ?: emptyList(),
            selectedEquips = selectedEquips,
            selectedChefs = selectedChefs,
            selectedRecipes = selectedRecipes,
            selectedEquipSlotIndex = selectedEquipSlotIndex,
            skills = gameData?.skills ?: emptyList(),
            ultimateSkills = ultimateSkills,
            allChefs = gameData?.chefs ?: emptyList(),
            allRecipes = gameData?.recipes ?: emptyList(),
            enabledAuraChefs = globalEnabledAuraChefs,
            filterSkill = equipFilterSkill,
            filterRarity1 = equipFilterRarity1,
            filterRarity2 = equipFilterRarity2,
            filterRarity3 = equipFilterRarity3,
            gameData = gameData,
            onFilterSkillChange = { 
                equipFilterSkill = it
                settingsStorage.saveEquipFilterSkill(it)
            },
            onFilterRarity1Change = { 
                equipFilterRarity1 = it
                settingsStorage.saveEquipFilterRarity(it, equipFilterRarity2, equipFilterRarity3)
            },
            onFilterRarity2Change = { 
                equipFilterRarity2 = it
                settingsStorage.saveEquipFilterRarity(equipFilterRarity1, it, equipFilterRarity3)
            },
            onFilterRarity3Change = { 
                equipFilterRarity3 = it
                settingsStorage.saveEquipFilterRarity(equipFilterRarity1, equipFilterRarity2, it)
            },
            onEquipSelected = { equip ->
                if (selectedEquipSlotIndex >= 0 && selectedEquipSlotIndex < 3) {
                    val newList = selectedEquips.toMutableList()
                    // 确保列表有足够的元素，但不添加空厨具
                    while (newList.size <= selectedEquipSlotIndex) {
                        newList.add(Equip(name = "")) // 添加占位厨具，名称为空
                    }
                    newList[selectedEquipSlotIndex] = equip
                    selectedEquips = newList
                }
                showEquipDialog = false
            },
            onClearCurrentEquip = {
                // 只清空当前选择框的厨具
                if (selectedEquipSlotIndex >= 0 && selectedEquipSlotIndex < selectedEquips.size) {
                    val newList = selectedEquips.toMutableList()
                    newList[selectedEquipSlotIndex] = Equip(name = "") // 设置为空厨具
                    selectedEquips = newList
                }
            },
            onDismiss = { showEquipDialog = false }
        )
    }

    // 菜谱选择对话框
    if (showRecipeDialog) {
        RecipeSelectionDialog(
            recipes = gameData?.recipes ?: emptyList(),
            selectedRecipes = selectedRecipes,
            selectedChefs = selectedChefs,
            selectedEquips = selectedEquips,
            selectedRecipeSlotIndex = selectedRecipeSlotIndex,
            skills = gameData?.skills ?: emptyList(),
            ultimateSkills = ultimateSkills,
            chefInteractions = chefInteractions,
            onlyShowOwned = onlyShowOwnedRecipes,
            onOnlyShowOwnedChange = {
                onlyShowOwnedRecipes = it
                settingsStorage.saveFilterOwnedRecipes(it)
            },
            settingsStorage = settingsStorage,
            gameData = gameData,
            onRecipeSelected = { recipe ->
                if (selectedRecipeSlotIndex >= 0 && selectedRecipeSlotIndex < 9) {
                    val newList = selectedRecipes.toMutableList()
                    // 确保列表足够长，用空Recipe填充
                    while (newList.size <= selectedRecipeSlotIndex) {
                        newList.add(Recipe()) // 添加空Recipe
                    }
                    newList[selectedRecipeSlotIndex] = recipe
                    selectedRecipes = newList
                    
                    // 手动选择菜谱时自动计算份数
                    calculateManualRecipePortions()
                }
                showRecipeDialog = false
            },
            onClearCurrentRecipe = {
                // 只清空当前选择框的菜谱
                if (selectedRecipeSlotIndex >= 0 && selectedRecipeSlotIndex < selectedRecipes.size) {
                    val newList = selectedRecipes.toMutableList()
                    newList[selectedRecipeSlotIndex] = Recipe(name = "") // 设置为空菜谱
                    selectedRecipes = newList
                    
                    // 清空菜谱时重新计算份数
                    calculateManualRecipePortions()
                }
            },
            onDismiss = { showRecipeDialog = false }
        )
    }

    // 设置对话框
    if (showSettingsDialog) {
        SettingsDialog(
            gameData = gameData,
            personalData = personalData,
            onDismiss = {
                showSettingsDialog = false
                // 更新全局光环厨师设置状态
                globalEnabledAuraChefs = settingsStorage.getSelectedAuraChefs()
            }
        )
    }
    
    // 使用说明弹窗
    if (showUsageDialog) {
        RecipeCalculatorUsageGuideDialog(
            onDismiss = { showUsageDialog = false }
        )
    }
    }
}

/**
 * 技法行组件 - 显示一行技法，每个技法单独设置颜色
 */
@Composable
private fun SkillRow(
    chef: Chef,
    ultimateSkills: UltimateSkillsState,
    equip: Equip?,
    skills: List<Skill>,
    chefInteractionBonus: Map<String, Int>?,
    skillTypes: List<String>,
    skillNames: List<String>,
    gameData: GameData?
) {
    val enhancedChef = ChefSkillCalculator.applyAllSkillsV2(chef, ultimateSkills, equip, skills, chefInteractionBonus, gameData)

    Row {
        skillTypes.forEachIndexed { index, skillType ->
            val skillValue = when (skillType) {
                "stirfry" -> enhancedChef.stirfry
                "boil" -> enhancedChef.boil
                "knife" -> enhancedChef.knife
                "fry" -> enhancedChef.fry
                "bake" -> enhancedChef.bake
                "steam" -> enhancedChef.steam
                else -> 0
            }

            val skillColor = when {
                ChefSkillCalculator.hasSpecificChefInteractionBonus(chefInteractionBonus, skillType) &&
                ChefSkillCalculator.hasSpecificEquipSkillBonus(chef, equip, skills, skillType) ->
                    Color(0xFF9C27B0) // 紫色：同时有厨师间技法影响和厨具技能加成
                ChefSkillCalculator.hasSpecificChefInteractionBonus(chefInteractionBonus, skillType) ->
                    MaterialTheme.colorScheme.primary // 蓝色：厨师间技法影响
                ChefSkillCalculator.hasSpecificEquipSkillBonus(chef, equip, skills, skillType) ->
                    Color(0xFF4CAF50) // 绿色：厨具技能加成
                else -> MaterialTheme.colorScheme.onSurfaceVariant // 正常颜色：包括个人技法加成
            }

            Text(
                text = "${skillNames[index]}${skillValue.toString().padStart(3)}",
                fontSize = 8.sp,
                color = skillColor,
                fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
            )

            if (index < skillTypes.size - 1) {
                Text(
                    text = " ",
                    fontSize = 8.sp,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
                )
            }
        }
    }
}

/**
 * 自选页面（完全按照web项目自选页面结构）
 */
@Composable
private fun CustomSelectionPage(
    selectedChefs: List<Chef>,
    selectedEquips: List<Equip>,
    selectedRecipes: List<Recipe>,
    recipePortions: List<Int>,
    skills: List<Skill>,
    ultimateSkills: UltimateSkillsState,
    recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState,
    allChefs: List<Chef>,
    allRecipes: List<Recipe>,
    totalScore: Int,
    totalTime: Int,
    efficiency: Int,
    goldPerHour: Int,
    enabledAuraChefs: Set<String>,
    gameData: GameData?,
    onChefClick: (Int) -> Unit,
    onEquipClick: (Int) -> Unit,
    onRecipeClick: (Int) -> Unit
) {
    // 计算厨师间技法影响
    val chefInteractions = remember(selectedChefs, skills, enabledAuraChefs) {
        ChefInteractionCalculator.calculateChefInteractions(selectedChefs, skills, enabledAuraChefs)
    }

    Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // selected-item-wrapper（选择项目区域）
        SelectedItemWrapper(
            selectedChefs = selectedChefs,
            selectedEquips = selectedEquips,
            selectedRecipes = selectedRecipes,
            recipePortions = recipePortions,
            skills = skills,
            ultimateSkills = ultimateSkills,
            recipeLimits = recipeLimits,
            allChefs = allChefs,
            allRecipes = allRecipes,
            chefInteractions = chefInteractions,
            gameData = gameData,
            onChefClick = onChefClick,
            onEquipClick = onEquipClick,
            onRecipeClick = onRecipeClick
        )
    }
}

/**
 * 选择项目包装器（selected-item-wrapper）- 完全按照web项目结构
 */
@Composable
private fun SelectedItemWrapper(
    selectedChefs: List<Chef>,
    selectedEquips: List<Equip>,
    selectedRecipes: List<Recipe>,
    recipePortions: List<Int>,
    skills: List<Skill>,
    ultimateSkills: UltimateSkillsState,
    recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState,
    allChefs: List<Chef>,
    allRecipes: List<Recipe>,
    chefInteractions: List<Map<String, Int>>,
    gameData: GameData?,
    onChefClick: (Int) -> Unit,
    onEquipClick: (Int) -> Unit,
    onRecipeClick: (Int) -> Unit
) {
    // 按照web项目，selected-item-wrapper里面只有一个selected-item
    // 这个selected-item包含所有的选择框（厨师、厨具、菜谱等）
    SelectedItem(
        selectedChefs = selectedChefs,
        selectedEquips = selectedEquips,
        selectedRecipes = selectedRecipes,
        recipePortions = recipePortions,
        skills = skills,
        ultimateSkills = ultimateSkills,
        recipeLimits = recipeLimits,
        allChefs = allChefs,
        allRecipes = allRecipes,
        chefInteractions = chefInteractions,
        gameData = gameData,
        onChefClick = onChefClick,
        onEquipClick = onEquipClick,
        onRecipeClick = onRecipeClick
    )
}

/**
 * 选择项目（selected-item）- 3列，每列1个厨师+1个厨具+3个菜谱
 */
@Composable
private fun SelectedItem(
    selectedChefs: List<Chef>,
    selectedEquips: List<Equip>,
    selectedRecipes: List<Recipe>,
    recipePortions: List<Int>,
    skills: List<Skill>,
    ultimateSkills: UltimateSkillsState,
    recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState,
    allChefs: List<Chef>,
    allRecipes: List<Recipe>,
    chefInteractions: List<Map<String, Int>>,
    gameData: GameData?,
    onChefClick: (Int) -> Unit,
    onEquipClick: (Int) -> Unit,
    onRecipeClick: (Int) -> Unit
) {
    // 3列布局，每列包含：1个厨师 + 1个厨具 + 3个菜谱
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        repeat(3) { columnIndex ->
            // 每一列
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                // 厨师选择框
                ChefBox(
                    chef = selectedChefs.getOrNull(columnIndex),
                    equip = selectedEquips.getOrNull(columnIndex),
                    skills = skills,
                    ultimateSkills = ultimateSkills,
                    chefInteractionBonus = chefInteractions.getOrNull(columnIndex),
                    gameData = gameData,
                    onClick = { onChefClick(columnIndex) },
                    modifier = Modifier.fillMaxWidth()
                )

                // 厨具选择框
                EquipBox(
                    equip = selectedEquips.getOrNull(columnIndex),
                    skills = skills,
                    allChefs = allChefs,
                    allRecipes = allRecipes,
                    onClick = { onEquipClick(columnIndex) },
                    modifier = Modifier.fillMaxWidth()
                )

                // 3个菜谱选择框
                repeat(3) { recipeIndex ->
                    val globalRecipeIndex = columnIndex * 3 + recipeIndex
                    RecipeBox(
                        recipe = selectedRecipes.getOrNull(globalRecipeIndex),
                        chef = selectedChefs.getOrNull(columnIndex),
                        equip = selectedEquips.getOrNull(columnIndex),
                        skills = skills,
                        ultimateSkills = ultimateSkills,
                        recipeLimits = recipeLimits,
                        chefInteractionBonus = chefInteractions.getOrNull(columnIndex),
                        actualPortions = recipePortions.getOrNull(globalRecipeIndex),
                        gameData = gameData,
                        onClick = { onRecipeClick(globalRecipeIndex) },
                        modifier = Modifier.fillMaxWidth()
                    )
                }
            }
        }
    }
}

/**
 * 厨师选择框（chef-box）
 */
@Composable
private fun ChefBox(
    chef: Chef?,
    equip: Equip?,
    skills: List<Skill>,
    ultimateSkills: UltimateSkillsState,
    chefInteractionBonus: Map<String, Int>? = null,
    gameData: GameData? = null,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .aspectRatio(1f) // 保持正方形比例
            .clickable { onClick() },
        colors = DeviceCompatibility.getAdaptiveCardColors(),
        border = BorderStroke(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
        )
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            if (chef != null && chef.name.isNotEmpty()) {
                // 显示厨师详细信息
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(4.dp),
                    verticalArrangement = Arrangement.spacedBy(1.dp)
                ) {
                    // 第一行：厨师名称 + 星级
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                    Text(
                        text = chef.name,
                        fontSize = 10.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary,
                            maxLines = 1
                        )

                        Spacer(modifier = Modifier.width(4.dp))

                        // 星级显示
                        repeat(chef.rarity) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier.size(8.dp)
                            )
                        }
                    }

                    // 第二行和第三行：技法数值分两行显示，每个技法单独设置颜色
                    Column(
                        verticalArrangement = Arrangement.spacedBy(0.5.dp)
                    ) {
                        // 第一行：炒、煮、切
                        SkillRow(
                            chef = chef,
                            ultimateSkills = ultimateSkills,
                            equip = equip,
                            skills = skills,
                            chefInteractionBonus = chefInteractionBonus,
                            skillTypes = listOf("stirfry", "boil", "knife"),
                            skillNames = listOf("炒", "煮", "切"),
                            gameData = gameData
                        )
                        // 第二行：炸、烤、蒸
                        SkillRow(
                            chef = chef,
                            ultimateSkills = ultimateSkills,
                            equip = equip,
                            skills = skills,
                            chefInteractionBonus = chefInteractionBonus,
                            skillTypes = listOf("fry", "bake", "steam"),
                            skillNames = listOf("炸", "烤", "蒸"),
                            gameData = gameData
                        )
                    }

                    // 第四行及以后：来源 + 是否已拥有
                    val originText = chef.origin.replace("<br>", "\n")

                    // 来源信息和状态显示
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = originText,
                            fontSize = 8.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 2, // 允许最多2行显示
                            lineHeight = 9.sp,
                            modifier = Modifier.weight(1f)
                        )

                        // 拥有状态和修炼状态显示（未拥有时只显示拥有状态）
                        Text(
                            text = buildAnnotatedString {
                                // 拥有状态
                                withStyle(
                                    style = SpanStyle(
                                        color = if (chef.got) MaterialTheme.colorScheme.primary else Color.Red,
                                        fontWeight = if (chef.got) FontWeight.Bold else FontWeight.Normal
                                    )
                                ) {
                                    append(if (chef.got) "已拥有" else "未拥有")
                                }
                                
                                // 只有已拥有时才显示修炼状态
                                if (chef.got) {
                                    append("\n")
                                    // 修炼状态
                                    withStyle(
                                        style = SpanStyle(
                                            color = if (chef.ult) MaterialTheme.colorScheme.primary else Color.Red,
                                            fontWeight = if (chef.ult) FontWeight.Bold else FontWeight.Normal
                                        )
                                    ) {
                                        append(if (chef.ult) "已修炼" else "未修炼")
                                    }
                                }
                            },
                            fontSize = 8.sp,
                            lineHeight = 10.sp,
                            textAlign = TextAlign.End
                        )
                    }
                }
            } else {
                // 厨师占位符（chef-placeholder）
                Text(
                    text = "+ 厨师",
                    fontSize = 10.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

/**
 * 厨具选择框（equip-box）
 */
@Composable
private fun EquipBox(
    equip: Equip?,
    skills: List<Skill>,
    allChefs: List<Chef>,
    allRecipes: List<Recipe>,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .height(DeviceCompatibility.getAdaptiveHeight(90.dp)) // 增加高度以容纳技能多行显示
            .clickable { onClick() },
        colors = DeviceCompatibility.getAdaptiveCardColors(),
        border = BorderStroke(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
        )
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            if (equip != null && equip.name.isNotEmpty()) {
                // 显示厨具信息 - 三行布局
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(6.dp), // 与菜谱选择框保持一致
                    verticalArrangement = Arrangement.spacedBy(3.dp) // 稍微增加行间距以避免重叠
                ) {
                    // 第一行：厨具名 + 星级（紧贴显示）
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = equip.name,
                            fontSize = 9.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary,
                            maxLines = 1
                        )

                        Spacer(modifier = Modifier.width(4.dp))

                        // 星级显示（紧贴厨具名）
                        repeat(equip.rarity) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier.size(8.dp)
                            )
                        }
                    }
                    
                    // 第二行：技能描述（允许多行显示）
                    val skillDesc = getEquipSkillDescription(equip, skills)
                    if (skillDesc.isNotEmpty()) {
                        Text(
                            text = skillDesc,
                            fontSize = 8.sp,
                            color = MaterialTheme.colorScheme.primary,
                            maxLines = 3, // 允许最多3行显示技能描述
                            lineHeight = 10.sp, // 稍微增加行高以提高可读性
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(min = 10.dp, max = 32.dp) // 限制技能描述区域的高度范围
                        )
                    } else {
                        Spacer(modifier = Modifier.height(10.dp))
                    }
                    
                    // 第三行：来源信息（左对齐）+ 拥有状态（右对齐）
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f), // 让第三行占用剩余空间
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically // 让来源和状态文字水平居中对齐
                    ) {
                        // 来源信息（左对齐）
                        if (equip.origin.isNotEmpty()) {
                            val originText = equip.origin.replace("<br>", "\n")
                            Text(
                                text = originText,
                                fontSize = 7.sp,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                maxLines = 2, // 允许最多2行显示
                                lineHeight = 8.sp,
                                modifier = Modifier
                                    .weight(1f)
                                    .padding(end = 4.dp) // 添加右边距，避免与状态文字贴太近
                            )
                        } else {
                            Spacer(modifier = Modifier.weight(1f))
                        }

                        // 拥有状态（右对齐）
                        val equipStatus = getEquipOwnershipStatus(equip, allRecipes)
                        Text(
                            text = equipStatus.text,
                            fontSize = 8.sp, // 稍微减小字体以节省空间
                            color = equipStatus.color, // 直接使用状态返回的颜色
                            fontWeight = if (equipStatus.text == "已拥有") FontWeight.Bold else FontWeight.Normal,
                            textAlign = TextAlign.End
                        )
                    }
                }
            } else {
                // 厨具占位符
                Text(
                    text = "+ 厨具",
                    fontSize = 10.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

/**
 * 菜谱选择框（recipe-box）- 按照web项目结构
 */
@Composable
private fun RecipeBox(
    recipe: Recipe?,
    chef: Chef?,
    equip: Equip?,
    skills: List<Skill>,
    ultimateSkills: UltimateSkillsState,
    recipeLimits: com.example.show_auto.ui.pages.RecipeLimitsState,
    chefInteractionBonus: Map<String, Int>? = null,
    actualPortions: Int? = null, // 一键查询的实际分配份数
    gameData: GameData? = null,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .height(DeviceCompatibility.getAdaptiveHeight(85.dp)) // 增加高度以完整显示三行内容
            .clickable { onClick() },
        colors = if (recipe != null && recipe.name.isNotEmpty()) {
            getChefBoxCompatibleCardColors()
            } else {
            DeviceCompatibility.getAdaptiveCardColors()
        },
        border = BorderStroke(
            width = 1.dp,
            color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
        )
    ) {
        if (recipe != null && recipe.name.isNotEmpty()) {
            // 显示菜谱信息
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(6.dp),
                verticalArrangement = Arrangement.spacedBy(1.dp)
            ) {
                // 第一行：菜谱名（左对齐）+ 品级
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = recipe.name,
                        fontSize = 9.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.secondary,
                        maxLines = 1,
                        modifier = Modifier.weight(1f)
                    )

                    // 品级显示（如果有厨师）
                    if (chef != null) {
                        val enhancedChef = ChefSkillCalculator.applyAllSkillsV2(
                            chef, ultimateSkills, equip, skills, chefInteractionBonus, gameData
                        )
                        val rank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)
                        val rankText = RecipeRankCalculator.getRankShortText(rank)
                        val rankColor = RecipeRankCalculator.getRankColor(rank)

                Text(
                            text = rankText,
                            fontSize = 10.sp,
                            color = Color(rankColor),
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.width(2.dp)) // 缩短间隔
                        
                        // 计算并显示最大制作份数
                        val basePortions = when (recipe.rarity) {
                            1 -> 40  // 1星菜谱基础份数
                            2 -> 30  // 2星菜谱基础份数
                            3 -> 25  // 3星菜谱基础份数
                            4 -> 20  // 4星菜谱基础份数
                            5 -> 15  // 5星菜谱基础份数
                            else -> 0 // 默认份数
                        }
                        
                        val limitBonus = when (recipe.rarity) {
                            1 -> recipeLimits.star1
                            2 -> recipeLimits.star2
                            3 -> recipeLimits.star3
                            4 -> recipeLimits.star4
                            5 -> recipeLimits.star5
                            else -> 0
                        }
                        
                        val maxPortions = basePortions + limitBonus
                        
                        // 如果有一键查询的实际分配份数，显示实际份数；否则显示最大份数
                        val displayPortions = actualPortions ?: maxPortions
                        
                        Text(
                            text = "${displayPortions}份",
                    fontSize = 8.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            fontWeight = FontWeight.Normal
                        )
                    }
                }

                // 第二行：星级（左对齐）+ 技法（右对齐）
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 星级显示（左对齐）
                    val starText = when (recipe.rarity) {
                        1 -> "一🔥"
                        2 -> "二🔥"
                        3 -> "三🔥"
                        4 -> "四🔥"
                        5 -> "五🔥"
                        else -> "${recipe.rarity}🔥"
                    }
                    Text(
                        text = starText,
                        fontSize = 9.sp,
                        color = MaterialTheme.colorScheme.primary,
                        fontWeight = FontWeight.Medium
                    )

                    Spacer(modifier = Modifier.weight(1f))

                    // 技法值（右对齐）
                    if (chef != null) {
                        val enhancedChef = ChefSkillCalculator.applyAllSkillsV2(
                            chef, ultimateSkills, equip, skills, chefInteractionBonus, gameData
                        )
                        val rank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)

                        if (rank >= 4) {
                            // 达到神级时显示菜谱技法需求
                            Text(
                                text = getRecipeSkillText(recipe).ifEmpty { "无技法" },
                                fontSize = 9.sp,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                maxLines = 1
                            )
                        } else {
                            // 未达到神级时显示技法差值，支持分段颜色显示
                            val (_, skillGaps) = getSkillGapText(enhancedChef, recipe)
                            
                            if (skillGaps.isNotEmpty()) {
                                Row {
                                    skillGaps.forEachIndexed { index, (skillText, isNegative) ->
                                        if (index > 0) {
                                            Text(
                                                text = " ",
                                                fontSize = 9.sp,
                                                color = MaterialTheme.colorScheme.onSurfaceVariant
                                            )
                                        }
                                        Text(
                                            text = skillText,
                                            fontSize = 9.sp,
                                            color = if (isNegative) Color.Red else MaterialTheme.colorScheme.onSurfaceVariant,
                                            maxLines = 1
                                        )
                                    }
                                }
                            } else {
                                Text(
                                    text = "无技法",
                                    fontSize = 9.sp,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    maxLines = 1
                                )
                            }
                        }
                    } else {
                        // 没有厨师时显示菜谱技法需求
                        Text(
                            text = getRecipeSkillText(recipe).ifEmpty { "无技法" },
                            fontSize = 9.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 1
                        )
                    }
                }

                // 第三行：来源（左对齐）+ 拥有状态（右对齐）
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 菜谱来源（左对齐）
                    if (recipe.origin.isNotEmpty()) {
                        val originText = recipe.origin.replace("<br>", "\n")
                        Text(
                            text = originText,
                            fontSize = 8.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 2, // 允许最多2行显示
                            lineHeight = 9.sp,
                            modifier = Modifier.weight(1f)
                        )
                    } else {
                        Spacer(modifier = Modifier.weight(1f))
                    }

                    // 拥有状态（右对齐）
                    Text(
                        text = if (recipe.got) "已拥有" else "未拥有",
                        fontSize = 9.sp,
                        color = if (recipe.got) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            Color.Red
                        },
                        fontWeight = if (recipe.got) FontWeight.Bold else FontWeight.Normal
                    )
                }
            }
        } else {
            // 空状态
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "+ 菜谱",
                    fontSize = 10.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}
/**
 * 厨师选择对话框
 */
@Composable
private fun ChefSelectionDialog(
    chefs: List<Chef>,
    selectedChefs: List<Chef>,
    skills: List<Skill>,
    ultimateSkills: UltimateSkillsState,
    onlyShowOwned: Boolean,
    onOnlyShowOwnedChange: (Boolean) -> Unit,
    onlyShowAuraChefs: Boolean,
    onOnlyShowAuraChefsChange: (Boolean) -> Unit,
    onlyShowUltimateChefs: Boolean,
    onOnlyShowUltimateChefsChange: (Boolean) -> Unit,
    onlyShowNonUltimateChefs: Boolean,
    onOnlyShowNonUltimateChefsChange: (Boolean) -> Unit,
    onChefSelected: (Chef) -> Unit,
    onClearCurrentChef: () -> Unit,
    onDismiss: () -> Unit
) {
    var searchText by remember { mutableStateOf("") }

    // 过滤厨师列表 - 根据开关状态决定是否只显示已拥有的厨师，支持技能搜索、光环厨师筛选、已修炼厨师筛选和未修炼厨师筛选
    val filteredChefs = remember(chefs, selectedChefs, searchText, onlyShowOwned, onlyShowAuraChefs, onlyShowUltimateChefs, onlyShowNonUltimateChefs, skills) {
        chefs.filter { chef ->
            // 基础过滤：排除已选择的厨师和搜索匹配（名称、技能描述或来源）
            val searchMatches = if (searchText.isEmpty()) {
                true
            } else {
                // 匹配厨师名称
                val nameMatches = chef.name.contains(searchText, ignoreCase = true)
                // 匹配技能描述
                val skillMatches = getChefSkillDescription(chef, skills).contains(searchText, ignoreCase = true)
                // 匹配厨师来源
                val originMatches = chef.origin.contains(searchText, ignoreCase = true)
                nameMatches || skillMatches || originMatches
            }

            // 光环厨师筛选
            val auraMatches = if (onlyShowAuraChefs) {
                isAuraChef(chef, skills) // 使用统一的光环厨师筛选逻辑
            } else {
                true
            }

            // 修炼状态筛选 - 修复逻辑：当两个都开启时显示所有厨师
            val cultivationMatches = when {
                onlyShowUltimateChefs && onlyShowNonUltimateChefs -> true // 两个都开启：显示所有厨师
                onlyShowUltimateChefs -> chef.ult // 只开启"查询已修"：只显示已修炼厨师
                onlyShowNonUltimateChefs -> !chef.ult // 只开启"查询未修"：只显示未修炼厨师
                else -> true // 两个都不开启：显示所有厨师
            }

            (!onlyShowOwned || chef.got) && // 如果开启"只查已拥有"，则只显示已拥有的厨师
            !selectedChefs.filter { it.name.isNotEmpty() }.contains(chef) && searchMatches && auraMatches && cultivationMatches
        }.sortedWith { chef1, chef2 ->
            // 按厨师ID降序排序（ID越大越靠前）
            val id1 = chef1.chefId.toIntOrNull() ?: 0
            val id2 = chef2.chefId.toIntOrNull() ?: 0
            id2.compareTo(id1)
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text("选择厨师")
        },
        text = {
            Column {
                // 筛选按钮组 - 移动到标题下方
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    // 查询已有按钮
                    Button(
                        onClick = { onOnlyShowOwnedChange(!onlyShowOwned) },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (onlyShowOwned)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (onlyShowOwned)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text(
                            text = "查询已有",
                            fontSize = 12.sp
                        )
                    }

                    // 查询光环按钮
                    Button(
                        onClick = { onOnlyShowAuraChefsChange(!onlyShowAuraChefs) },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (onlyShowAuraChefs)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (onlyShowAuraChefs)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                ) {
                    Text(
                            text = "查询光环",
                            fontSize = 12.sp
                        )
                    }

                    // 查询已修炼按钮
                    Button(
                        onClick = { onOnlyShowUltimateChefsChange(!onlyShowUltimateChefs) },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(0.dp), // 移除内边距，让文字居中
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (onlyShowUltimateChefs)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (onlyShowUltimateChefs)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text(
                            text = "查询已修炼",
                        fontSize = 12.sp,
                            textAlign = TextAlign.Center // 添加文字居中
                        )
                    }

                    // 查询未修炼按钮
                    Button(
                        onClick = { onOnlyShowNonUltimateChefsChange(!onlyShowNonUltimateChefs) },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(0.dp), // 移除内边距，让文字居中
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (onlyShowNonUltimateChefs)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (onlyShowNonUltimateChefs)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text(
                            text = "查询未修炼",
                            fontSize = 12.sp,
                            textAlign = TextAlign.Center // 添加文字居中
                        )
                    }
                }

                // 搜索框 - 按照web项目的live-search，支持技能搜索
                OutlinedTextField(
                    value = searchText,
                    onValueChange = { searchText = it },
                    label = { Text("查找", fontSize = 13.sp) },
                    placeholder = { Text("输入厨师名称、技能或来源", fontSize = 13.sp) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索",
                            modifier = Modifier.size(20.dp)
                        )
                    },
                    trailingIcon = {
                        if (searchText.isNotEmpty()) {
                            IconButton(onClick = { searchText = "" }) {
                                Icon(
                                    imageVector = Icons.Default.Clear,
                                    contentDescription = "清空",
                                    modifier = Modifier.size(18.dp)
                                )
                            }
                        }
                    },
                    shape = RoundedCornerShape(8.dp)
                )

                Spacer(modifier = Modifier.height(8.dp))

                // 厨师列表
                LazyColumn(
                    modifier = Modifier.height(400.dp)
                ) {
                    if (filteredChefs.isEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = if (searchText.isEmpty()) "没有可选厨师" else "没有找到",
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    } else {
                        items(filteredChefs) { chef ->
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 2.dp)
                                    .clickable { onChefSelected(chef) },
                                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                            ) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(12.dp)
                                ) {
                                    // 主要内容区域
                                    Column {
                                        // 第一行：厨师名字 + 星级
                                        Row(
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                        Text(
                                            text = chef.name,
                                            fontSize = 16.sp,
                                            fontWeight = FontWeight.Medium
                                        )

                                            Spacer(modifier = Modifier.width(8.dp))

                                            // 星级显示
                                            Row {
                                                repeat(chef.rarity) {
                                                    Icon(
                                                        imageVector = Icons.Default.Star,
                                                        contentDescription = null,
                                                        tint = MaterialTheme.colorScheme.primary,
                                                        modifier = Modifier.size(12.dp)
                                                    )
                                                }
                                            }
                                        }

                                        // 第二行：技能描述
                                        Text(
                                            text = getChefSkillDescription(chef, skills),
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.primary,
                                            modifier = Modifier.padding(top = 4.dp)
                                        )

                                        // 第三行：来源
                                        Text(
                                            text = chef.origin.replace("<br>", "、"),
                                            fontSize = 13.sp,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                                            modifier = Modifier.padding(top = 2.dp)
                                        )
                                    }
                                    
                                    // 右下角：拥有状态和修炼状态
                                    Column(
                                        modifier = Modifier.align(Alignment.BottomEnd),
                                        horizontalAlignment = Alignment.End
                                    ) {
                                        // 拥有状态
                                        Text(
                                            text = if (chef.got) "已拥有" else "未拥有",
                                            fontSize = 9.sp,
                                            color = if (chef.got)
                                                MaterialTheme.colorScheme.primary
                                            else
                                                Color.Red,
                                            fontWeight = if (chef.got) FontWeight.Bold else FontWeight.Normal
                                        )

                                        // 只有已拥有的厨师才显示修炼状态
                                        if (chef.got) {
                                        Text(
                                            text = if (chef.ult) "已修炼" else "未修炼",
                                            fontSize = 9.sp,
                                            color = if (chef.ult)
                                                MaterialTheme.colorScheme.primary
                                            else
                                                Color.Red,
                                            fontWeight = if (chef.ult) FontWeight.Bold else FontWeight.Normal
                                        )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            Row {
                if (searchText.isNotEmpty()) {
                    TextButton(onClick = { searchText = "" }) {
                        Text("清空搜索")
                    }
                }
                TextButton(onClick = {
                    onClearCurrentChef() // 只清空当前选择框的厨师数据
                    onDismiss() // 关闭对话框
                }) {
                    Text("清空当前")
                }
                TextButton(onClick = onDismiss) {
                    Text("关闭")
                }
            }
        }
    )
}

/**
 * 厨具选择对话框 - 带筛选功能
 */
@Composable
private fun EquipSelectionDialog(
    equips: List<Equip>,
    selectedEquips: List<Equip>,
    selectedChefs: List<Chef>,
    selectedRecipes: List<Recipe>,
    selectedEquipSlotIndex: Int,
    skills: List<Skill>,
    ultimateSkills: UltimateSkillsState,
    allChefs: List<Chef>,
    allRecipes: List<Recipe>,
    enabledAuraChefs: Set<String>,
    filterSkill: Boolean,
    filterRarity1: Boolean,
    filterRarity2: Boolean,
    filterRarity3: Boolean,
    gameData: GameData?,
    onFilterSkillChange: (Boolean) -> Unit,
    onFilterRarity1Change: (Boolean) -> Unit,
    onFilterRarity2Change: (Boolean) -> Unit,
    onFilterRarity3Change: (Boolean) -> Unit,
    onEquipSelected: (Equip) -> Unit,
    onClearCurrentEquip: () -> Unit,
    onDismiss: () -> Unit
) {
    var searchText by remember { mutableStateOf("") }
    var isRecommendationExpanded by remember { mutableStateOf(true) }

    // 计算厨师间技法影响
    val chefInteractions = remember(selectedChefs, skills, enabledAuraChefs) {
        ChefInteractionCalculator.calculateChefInteractions(selectedChefs, skills, enabledAuraChefs)
    }

    // 计算厨具推荐
    val equipRecommendation = remember(selectedChefs, selectedRecipes, selectedEquipSlotIndex, equips, skills, ultimateSkills, chefInteractions) {
        val chefIndex = selectedEquipSlotIndex
        val chef = selectedChefs.getOrNull(chefIndex)

        if (chef != null) {
            // 获取该厨师的三个菜谱
            val chefRecipes: List<Recipe?> = listOf(
                selectedRecipes.getOrNull(chefIndex * 3),
                selectedRecipes.getOrNull(chefIndex * 3 + 1),
                selectedRecipes.getOrNull(chefIndex * 3 + 2)
            )

            // 获取包含厨师间技法影响的厨师数据
            val chefWithInteractions = ChefSkillCalculator.applyAllSkillsV2(
                chef = chef,
                ultimateSkills = ultimateSkills,
                equip = null, // 不包含厨具，因为推荐算法会自己测试厨具
                skills = skills,
                chefInteractionBonus = chefInteractions.getOrNull(chefIndex),
                gameData = gameData
            )

            EquipRecommendationCalculator.calculateRecommendation(
                chef = chefWithInteractions,
                recipes = chefRecipes,
                allEquips = equips,
                skills = skills,
                ultimateSkills = UltimateSkillsState(), // 传递空的个人技法，因为已经应用到chefWithInteractions中了
                allChefs = allChefs,
                allRecipes = allRecipes
            )
        } else {
            EquipRecommendationCalculator.RecommendationResult(
                needRecommendation = false,
                targetRecipes = emptyList<Recipe>(),
                recommendedEquips = emptyList<EquipRecommendationCalculator.EquipRecommendation>()
            )
        }
    }

    // 过滤厨具列表
    val filteredEquips = remember(equips, selectedEquips, searchText, filterSkill, filterRarity1, filterRarity2, filterRarity3, skills) {
        equips.filter { equip ->
            // 基础过滤：搜索匹配（名称、技能描述或来源）- 允许重复选择厨具
            val searchMatches = if (searchText.isEmpty()) {
                true
            } else {
                // 匹配厨具名称
                val nameMatches = equip.name.contains(searchText, ignoreCase = true)
                // 匹配技能描述
                val skillMatches = getEquipSkillDescription(equip, skills).contains(searchText, ignoreCase = true)
                // 匹配厨具来源
                val originMatches = equip.origin.contains(searchText, ignoreCase = true)
                nameMatches || skillMatches || originMatches
            }
            
            if (!searchMatches) return@filter false
            
            // 技法加成筛选
            val skillFilter = if (filterSkill) {
                hasSkillBonus(equip, skills)
            } else {
                true
            }
            
            // 星级筛选
            val rarityFilter = when {
                filterRarity1 && equip.rarity == 1 -> true
                filterRarity2 && equip.rarity == 2 -> true
                filterRarity3 && equip.rarity == 3 -> true
                !filterRarity1 && !filterRarity2 && !filterRarity3 -> true // 没有星级筛选时显示所有
                else -> false
            }
            
            skillFilter && rarityFilter
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text("选择厨具")
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 600.dp) // 限制对话框最大高度
                    .verticalScroll(rememberScrollState()), // 添加垂直滚动功能
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 筛选按钮行 - 四个按钮填满一行
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            // 技法加成筛选按钮
                    Button(
                                onClick = { onFilterSkillChange(!filterSkill) },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                                shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterSkill)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterSkill)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                            ) {
                                Text(
                                    text = "技法",
                                    fontSize = 12.sp
                                )
                            }
                            
                            // 1星按钮
                    Button(
                                onClick = { onFilterRarity1Change(!filterRarity1) },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                                shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity1)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity1)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = null,
                                tint = if (filterRarity1)
                                    MaterialTheme.colorScheme.onPrimary // 选中时使用白色
                                else
                                    MaterialTheme.colorScheme.primary, // 未选中时使用深蓝色
                                modifier = Modifier.size(12.dp)
                            )
                        }
                            }
                            
                            // 2星按钮
                    Button(
                                onClick = { onFilterRarity2Change(!filterRarity2) },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                                shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity2)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity2)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            repeat(2) {
                                Icon(
                                    imageVector = Icons.Default.Star,
                                    contentDescription = null,
                                    tint = if (filterRarity2)
                                        MaterialTheme.colorScheme.onPrimary // 选中时使用白色
                                    else
                                        MaterialTheme.colorScheme.primary, // 未选中时使用深蓝色
                                    modifier = Modifier.size(12.dp)
                                )
                            }
                        }
                            }
                            
                            // 3星按钮
                    Button(
                                onClick = { onFilterRarity3Change(!filterRarity3) },
                        modifier = Modifier
                            .weight(1f)
                            .height(32.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity3)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity3)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            repeat(3) {
                                Icon(
                                    imageVector = Icons.Default.Star,
                                    contentDescription = null,
                                    tint = if (filterRarity3)
                                        MaterialTheme.colorScheme.onPrimary // 选中时使用白色
                                    else
                                        MaterialTheme.colorScheme.primary, // 未选中时使用深蓝色
                                    modifier = Modifier.size(12.dp)
                                )
                            }
                        }
                    }
                }

                // 厨具推荐区域
                if (equipRecommendation.needRecommendation) {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = getDarkGreyBackgroundColor()
                        )
                    ) {
                        Column(
                            modifier = Modifier.padding(12.dp)
                        ) {
                            // 标题行：厨具推荐 + 收起/展开按钮
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = "🔧 厨具推荐",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = MaterialTheme.colorScheme.primary
                                )

                                // 收起/展开按钮
                                IconButton(
                                    onClick = { isRecommendationExpanded = !isRecommendationExpanded },
                                    modifier = Modifier.size(24.dp)
                                ) {
                                    Icon(
                                        imageVector = if (isRecommendationExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                        contentDescription = if (isRecommendationExpanded) "收起推荐" else "展开推荐",
                                        tint = MaterialTheme.colorScheme.primary,
                                        modifier = Modifier.size(16.dp)
                                    )
                                }
                            }

                            Spacer(modifier = Modifier.height(4.dp))

                            Text(
                                text = EquipRecommendationCalculator.getRecommendationDescription(equipRecommendation),
                                fontSize = 12.sp,
                                color = MaterialTheme.colorScheme.onSurface
                            )

                            if (equipRecommendation.recommendedEquips.isNotEmpty() && isRecommendationExpanded) {
                                Spacer(modifier = Modifier.height(8.dp))

                                // 根据筛选条件过滤推荐厨具
                                val filteredRecommendations = equipRecommendation.recommendedEquips.filter { recommendation ->
                                    val equip = recommendation.equip

                                    // 技法筛选
                                    val passSkillFilter = if (filterSkill) {
                                        hasSkillBonus(equip, skills)
                                    } else true

                                    // 星级筛选
                                    val passRarityFilter = when {
                                        filterRarity1 && equip.rarity == 1 -> true
                                        filterRarity2 && equip.rarity == 2 -> true
                                        filterRarity3 && equip.rarity == 3 -> true
                                        !filterRarity1 && !filterRarity2 && !filterRarity3 -> true // 没有星级筛选时显示所有
                                        else -> false
                                    }

                                    passSkillFilter && passRarityFilter
                                }

                                // 可滑动的推荐厨具列表
                                LazyColumn(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .heightIn(max = 320.dp), // 增加最大高度，能显示更多厨具
                                    verticalArrangement = Arrangement.spacedBy(4.dp)
                                ) {
                                    items(filteredRecommendations) { recommendation ->
                                        Card(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .clickable { onEquipSelected(recommendation.equip) },
                                            colors = getChefBoxCompatibleCardColors(),
                                            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                                        ) {
                                            Box(
                                                modifier = Modifier
                                                    .fillMaxWidth()
                                                    .padding(8.dp)
                                            ) {
                                                Column(
                                                    modifier = Modifier.fillMaxWidth()
                                                ) {
                                                    // 第一行：厨具名称 + 星级 + 可能已有标识
                                                    Row(
                                                        modifier = Modifier.fillMaxWidth(),
                                                        verticalAlignment = Alignment.CenterVertically
                                                    ) {
                                                        Text(
                                                            text = recommendation.equip.name,
                                                            fontSize = 12.sp,
                                                            fontWeight = FontWeight.Medium
                                                        )

                                                        Spacer(modifier = Modifier.width(4.dp))

                                                        // 星级显示
                                                        Row {
                                                            repeat(recommendation.equip.rarity) {
                                                                Icon(
                                                                    imageVector = Icons.Default.Star,
                                                                    contentDescription = null,
                                                                    tint = MaterialTheme.colorScheme.primary,
                                                                    modifier = Modifier.size(12.dp)
                                                                )
                                                            }
                                                        }

                                                        // 拥有状态标识（紧贴星级）
                                                        Spacer(modifier = Modifier.width(4.dp))
                                                        val equipOrigins = recommendation.equip.origin.replace("<br>", "、").split("、").map { it.trim() }
                                                        val isAlreadyOwned = equipOrigins.any { origin ->
                                                            origin.contains("新手奖池") ||
                                                            origin.contains("中级奖池") ||
                                                            origin.contains("高级奖池") ||
                                                            origin.contains("碧池")
                                                        }

                                                        val (statusText, statusColor) = when {
                                                            isAlreadyOwned -> "已有" to Color(0xFF4CAF50) // 绿色
                                                            recommendation.isPossiblyOwned -> "可能已有" to Color(0xFFFFC107) // 黄色
                                                            else -> "未拥有" to Color(0xFFF44336) // 红色
                                                        }

                                                        Text(
                                                            text = statusText,
                                                            fontSize = 8.sp,
                                                            color = statusColor,
                                                            fontWeight = FontWeight.Bold
                                                        )
                                                    }

                                                    Spacer(modifier = Modifier.height(2.dp))

                                                    // 第二行：厨具技能描述
                                                    Text(
                                                        text = getEquipSkillDescription(recommendation.equip, skills),
                                                        fontSize = 10.sp,
                                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                                    )

                                                    Spacer(modifier = Modifier.height(2.dp))

                                                    // 第三行：能做到神级的菜谱
                                                    val recipeNames = recommendation.affectedRecipes.joinToString("、") { it.name }
                                                    Text(
                                                        text = "${recipeNames}(神)",
                                                        fontSize = 10.sp,
                                                        color = MaterialTheme.colorScheme.primary
                                                    )
                                                }

                                                // 右下角：来源
                                                Text(
                                                    text = recommendation.equip.origin.replace("<br>", "\n"),
                                                    fontSize = 8.sp,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                    modifier = Modifier.align(Alignment.BottomEnd)
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 搜索框
                OutlinedTextField(
                    value = searchText,
                    onValueChange = { searchText = it },
                    label = { Text("查找", fontSize = 13.sp) },
                    placeholder = { Text("输入厨具名称、技能或来源", fontSize = 13.sp) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp),
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索",
                            modifier = Modifier.size(20.dp)
                        )
                    },
                    trailingIcon = {
                        if (searchText.isNotEmpty()) {
                            IconButton(onClick = { searchText = "" }) {
                                Icon(
                                    imageVector = Icons.Default.Clear,
                                    contentDescription = "清空",
                                    modifier = Modifier.size(18.dp)
                                )
                            }
                        }
                    },
                    shape = RoundedCornerShape(8.dp)
                )

                // 厨具列表
                LazyColumn(
                    modifier = Modifier.height(400.dp)
                ) {
                    if (filteredEquips.isEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = if (searchText.isEmpty()) "没有可选择的厨具" else "没有找到",
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    } else {
                        items(filteredEquips) { equip ->
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 2.dp)
                                    .clickable { onEquipSelected(equip) },
                                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                            ) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(12.dp)
                                ) {
                                    // 主要内容区域
                                    Column {
                                        // 第一行：厨具名称、星级和拥有状态
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Text(
                                                text = equip.name,
                                                fontSize = 16.sp,
                                                fontWeight = FontWeight.Medium
                                            )
                                            Spacer(modifier = Modifier.width(8.dp))
                                            // 显示星级
                                            repeat(equip.rarity) {
                                                Icon(
                                                    imageVector = Icons.Default.Star,
                                                    contentDescription = null,
                                                    tint = MaterialTheme.colorScheme.primary,
                                                    modifier = Modifier.size(12.dp)
                                                )
                                            }
                                            
                                            Spacer(modifier = Modifier.weight(1f)) // 推到右侧
                                            
                                            // 厨具拥有状态显示
                                            val equipStatus = getEquipOwnershipStatus(equip, allRecipes)
                                            Text(
                                                text = equipStatus.text,
                                                fontSize = 9.sp,
                                                color = equipStatus.color,
                                                fontWeight = FontWeight.Bold
                                            )
                                        }

                                        // 第二行：技能描述和来源
                                        val skillDescription = getEquipSkillDescription(equip, skills)
                                        if (skillDescription.isNotEmpty() || equip.origin.isNotEmpty()) {
                                            Column(
                                                modifier = Modifier.padding(top = 4.dp)
                                            ) {
                                                Row(
                                                    modifier = Modifier.fillMaxWidth(),
                                                    horizontalArrangement = Arrangement.SpaceBetween,
                                                    verticalAlignment = Alignment.CenterVertically
                                                ) {
                                                    // 技能描述
                                        if (skillDescription.isNotEmpty()) {
                                            Text(
                                                text = skillDescription,
                                                fontSize = 14.sp,
                                                color = MaterialTheme.colorScheme.primary,
                                                            modifier = Modifier.weight(1f)
                                            )
                                        }
                                        
                                                    // 来源显示（前两个）
                                        if (equip.origin.isNotEmpty()) {
                                                        val origins = equip.origin.replace("<br>", "、").split("、")
                                                        val firstTwoOrigins = origins.take(2).joinToString("、")
                                            Text(
                                                            text = firstTwoOrigins,
                                                fontSize = 13.sp,
                                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                            modifier = Modifier.padding(start = 8.dp)
                                                        )
                                                    }
                                                }

                                                // 第三行：剩余来源（如果超过2个）
                                                if (equip.origin.isNotEmpty()) {
                                                    val origins = equip.origin.replace("<br>", "、").split("、")
                                                    if (origins.size > 2) {
                                                        val remainingOrigins = origins.drop(2).joinToString("、")
                                                        Row(
                                                            modifier = Modifier.fillMaxWidth(),
                                                            horizontalArrangement = Arrangement.End
                                                        ) {
                                                            Text(
                                                                text = remainingOrigins,
                                                                fontSize = 13.sp,
                                                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                                modifier = Modifier.padding(top = 2.dp)
                                                            )
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            Row {
                if (searchText.isNotEmpty()) {
                    TextButton(onClick = { searchText = "" }) {
                        Text("清空搜索")
                    }
                }
                TextButton(onClick = {
                    onClearCurrentEquip() // 只清空当前选择框的厨具数据
                    onDismiss() // 关闭对话框
                }) {
                    Text("清空当前")
                }
                TextButton(onClick = onDismiss) {
                    Text("关闭")
                }
            }
        }
    )
}

/**
 * 菜谱选择对话框
 */
@Composable
private fun RecipeSelectionDialog(
    recipes: List<Recipe>,
    selectedRecipes: List<Recipe>,
    selectedChefs: List<Chef>,
    selectedEquips: List<Equip>,
    selectedRecipeSlotIndex: Int,
    skills: List<Skill>,
    ultimateSkills: UltimateSkillsState,
    chefInteractions: List<Map<String, Int>>,
    onlyShowOwned: Boolean,
    onOnlyShowOwnedChange: (Boolean) -> Unit,
    settingsStorage: SettingsStorage,
    gameData: com.example.show_auto.data.GameData?, // 添加游戏数据参数
    onRecipeSelected: (Recipe) -> Unit,
    onClearCurrentRecipe: () -> Unit,
    onDismiss: () -> Unit
) {
    var searchText by remember { mutableStateOf("") }

    // 星级筛选状态 - 从存储中加载初始值
    var filterRarity1 by remember { mutableStateOf(settingsStorage.getRecipeFilterRarity1()) }
    var filterRarity2 by remember { mutableStateOf(settingsStorage.getRecipeFilterRarity2()) }
    var filterRarity3 by remember { mutableStateOf(settingsStorage.getRecipeFilterRarity3()) }
    var filterRarity4 by remember { mutableStateOf(settingsStorage.getRecipeFilterRarity4()) }
    var filterRarity5 by remember { mutableStateOf(settingsStorage.getRecipeFilterRarity5()) }
    
    // 技法筛选状态
    var skillFilter by remember { mutableStateOf("") } // 当前筛选的技法
    
    // 获取当前厨师用于自动设置筛选条件
    val chefIndex = selectedRecipeSlotIndex / 3
    val currentChef = selectedChefs.getOrNull(chefIndex)
    
    // 当选择厨师后，自动设置筛选条件
    LaunchedEffect(currentChef) {
        if (currentChef != null && gameData != null) {
            // 获取厨师的修炼任务
            val ultimateGoal = currentChef.ultimateGoal.firstOrNull()
            if (ultimateGoal != null) {
                val quest = gameData.quests.find { it.questId == ultimateGoal }
                val condition = quest?.conditions?.firstOrNull()
                if (condition != null) {
                    // 设置技法筛选
                    skillFilter = condition.skill
                    
                    // 设置星级筛选
                    val newRarity1 = condition.rarity == 1
                    val newRarity2 = condition.rarity == 2
                    val newRarity3 = condition.rarity == 3
                    val newRarity4 = condition.rarity == 4
                    val newRarity5 = condition.rarity == 5
                    
                    // 更新状态
                    filterRarity1 = newRarity1
                    filterRarity2 = newRarity2
                    filterRarity3 = newRarity3
                    filterRarity4 = newRarity4
                    filterRarity5 = newRarity5
                    
                    // 持久化星级筛选状态
                    settingsStorage.saveRecipeFilterRarity(newRarity1, newRarity2, newRarity3, newRarity4, newRarity5)
                    
                }
            }
        } else if (currentChef == null) {
            // 没有厨师时清空技法筛选
            skillFilter = ""
        }
    }

    // 过滤和排序菜谱列表
    val filteredRecipes = remember(recipes, selectedRecipes, searchText, onlyShowOwned, filterRarity1, filterRarity2, filterRarity3, filterRarity4, filterRarity5, skillFilter, selectedChefs, selectedEquips, selectedRecipeSlotIndex, skills, ultimateSkills, chefInteractions) {
        val baseFiltered = recipes.filter { recipe ->
            // 基础筛选
            val basicFilter = (!onlyShowOwned || recipe.got) && // 如果开启"只查已拥有"，则只显示已拥有的菜谱
            !selectedRecipes.contains(recipe) &&
            (searchText.isEmpty() ||
             recipe.name.contains(searchText, ignoreCase = true) ||
             recipe.origin.contains(searchText, ignoreCase = true) ||
             getRecipeSkillText(recipe).contains(searchText, ignoreCase = true))

            if (!basicFilter) return@filter false

            // 星级筛选
            val rarityFilter = when {
                filterRarity1 && recipe.rarity == 1 -> true
                filterRarity2 && recipe.rarity == 2 -> true
                filterRarity3 && recipe.rarity == 3 -> true
                filterRarity4 && recipe.rarity == 4 -> true
                filterRarity5 && recipe.rarity == 5 -> true
                !filterRarity1 && !filterRarity2 && !filterRarity3 && !filterRarity4 && !filterRarity5 -> true // 没有星级筛选时显示所有
                else -> false
            }

            // 技法筛选
            val skillFilterResult = if (skillFilter.isNotEmpty()) {
                hasRequiredSkill(recipe, skillFilter)
            } else {
                true // 没有技法筛选时显示所有
            }
            
            rarityFilter && skillFilterResult
        }

        // 获取对应的厨师用于品级排序
        val chefIndex = selectedRecipeSlotIndex / 3
        val chef = selectedChefs.getOrNull(chefIndex)
        val equip = selectedEquips.getOrNull(chefIndex)

        if (chef != null) {
            // 应用技法加成（包含厨师间技法影响）
            val enhancedChef = ChefSkillCalculator.applyAllSkillsV2(
                chef, ultimateSkills, equip, skills, chefInteractions.getOrNull(chefIndex), gameData
            )

            // 新排序逻辑：神级传级混合按时间排序，特级及以下按品级+神差值+时间排序
            baseFiltered.sortedWith { recipe1, recipe2 ->
                val rank1 = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe1)
                val rank2 = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe2)
                
                // 检查是否为神级或传级
                val isHighTier1 = rank1 >= 4 // 神级(4)或传级(5)
                val isHighTier2 = rank2 >= 4
                
                when {
                    // 如果都是神/传级，按时间排序（可以混合）
                    isHighTier1 && isHighTier2 -> recipe1.time.compareTo(recipe2.time)
                    // 如果一个是神/传级，另一个不是，优先神/传级
                    isHighTier1 && !isHighTier2 -> -1
                    !isHighTier1 && isHighTier2 -> 1
                    // 如果都不是神/传级（特级及以下），使用新的排序逻辑
                    else -> {
                        val rankComparison = rank2.compareTo(rank1) // 品级高到低
                        if (rankComparison != 0) {
                            rankComparison
                        } else {
                            // 品级相同时，使用神差值排序逻辑
                            compareByGodTierGaps(enhancedChef, recipe1, recipe2)
                        }
                    }
                }
            }
        } else {
            // 没有厨师时，按星级和时间排序
            baseFiltered.sortedWith(
                compareByDescending<Recipe> { it.rarity }
                    .thenBy { it.time }
            )
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text("选择菜谱")
        },
        text = {
            Column {
                // 筛选按钮组 - 移动到标题下方，6个按钮平均分配
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    horizontalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    // 查询已有按钮 - 放在第一个位置
                    Button(
                        onClick = { onOnlyShowOwnedChange(!onlyShowOwned) },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 2.dp, vertical = 2.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (onlyShowOwned)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (onlyShowOwned)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text(
                            text = "查询已有",
                            fontSize = 9.sp
                        )
                    }

                    // 1星按钮
                    Button(
                        onClick = {
                            filterRarity1 = !filterRarity1
                            settingsStorage.saveRecipeFilterRarity(filterRarity1, filterRarity2, filterRarity3, filterRarity4, filterRarity5)
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 2.dp, vertical = 2.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity1)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity1)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text("1星", fontSize = 9.sp)
                    }

                    // 2星按钮
                    Button(
                        onClick = {
                            filterRarity2 = !filterRarity2
                            settingsStorage.saveRecipeFilterRarity(filterRarity1, filterRarity2, filterRarity3, filterRarity4, filterRarity5)
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 2.dp, vertical = 2.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity2)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity2)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text("2星", fontSize = 9.sp)
                    }

                    // 3星按钮
                    Button(
                        onClick = {
                            filterRarity3 = !filterRarity3
                            settingsStorage.saveRecipeFilterRarity(filterRarity1, filterRarity2, filterRarity3, filterRarity4, filterRarity5)
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 2.dp, vertical = 2.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity3)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity3)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text("3星", fontSize = 9.sp)
                    }

                    // 4星按钮
                    Button(
                        onClick = {
                            filterRarity4 = !filterRarity4
                            settingsStorage.saveRecipeFilterRarity(filterRarity1, filterRarity2, filterRarity3, filterRarity4, filterRarity5)
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 2.dp, vertical = 2.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity4)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity4)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text("4星", fontSize = 9.sp)
                    }

                    // 5星按钮
                    Button(
                        onClick = {
                            filterRarity5 = !filterRarity5
                            settingsStorage.saveRecipeFilterRarity(filterRarity1, filterRarity2, filterRarity3, filterRarity4, filterRarity5)
                        },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(6.dp),
                        contentPadding = PaddingValues(horizontal = 2.dp, vertical = 2.dp),
                        border = BorderStroke(1.dp, Color.Black),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (filterRarity5)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (filterRarity5)
                                MaterialTheme.colorScheme.onPrimary
                            else
                                MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    ) {
                        Text("5星", fontSize = 9.sp)
                    }
                }

                // 搜索框
                OutlinedTextField(
                    value = searchText,
                    onValueChange = { searchText = it },
                    label = { Text("查找") },
                    placeholder = { Text("输入菜谱名称、来源或技法", fontSize = 12.sp) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索"
                        )
                    },
                    trailingIcon = {
                        if (searchText.isNotEmpty()) {
                            IconButton(onClick = { searchText = "" }) {
                                Icon(
                                    imageVector = Icons.Default.Clear,
                                    contentDescription = "清空"
                                )
                            }
                        }
                    }
                )

                Spacer(modifier = Modifier.height(8.dp))

                // 菜谱列表
                LazyColumn(
                    modifier = Modifier.height(400.dp)
                ) {
                    if (filteredRecipes.isEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = if (searchText.isEmpty()) "没有可选菜谱" else "没有找到",
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    } else {
                        items(filteredRecipes) { recipe ->
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 2.dp)
                                    .clickable { onRecipeSelected(recipe) },
                                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                            ) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(12.dp)
                                ) {
                                    // 主要内容区域
                                    Column {
                                        // 第一行：菜谱名字 + 星级（左侧） + 技法（右对齐）
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.SpaceBetween
                                        ) {
                                            // 左侧：菜谱名字 + 星级 + 时间
                                            Row(
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                        Text(
                                            text = recipe.name,
                                            fontSize = 14.sp,
                                            fontWeight = FontWeight.Medium
                                        )

                                                Spacer(modifier = Modifier.width(8.dp))

                                                // 星级显示（火焰格式）
                                                val starText = when (recipe.rarity) {
                                                    1 -> "一🔥"
                                                    2 -> "二🔥"
                                                    3 -> "三🔥"
                                                    4 -> "四🔥"
                                                    5 -> "五🔥"
                                                    else -> "${recipe.rarity}🔥"
                                                }
                                        Text(
                                                    text = starText,
                                            fontSize = 12.sp,
                                                    color = MaterialTheme.colorScheme.primary,
                                                    fontWeight = FontWeight.Medium
                                                )
                                                
                                                Spacer(modifier = Modifier.width(8.dp))
                                                
                                                // 时间显示（秒转换为分:秒格式）
                                                val minutes = recipe.time / 60
                                                val seconds = recipe.time % 60
                                                val timeText = if (minutes > 0) {
                                                    "${minutes}分${seconds}秒"
                                                } else {
                                                    "${seconds}秒"
                                                }
                                                Text(
                                                    text = timeText,
                                                    fontSize = 11.sp,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }

                                            // 右侧：技法显示（右对齐）
                                            val chefIndex = selectedRecipeSlotIndex / 3
                                            val chef = selectedChefs.getOrNull(chefIndex)
                                            val equip = selectedEquips.getOrNull(chefIndex)
                                            
                                            if (chef != null) {
                                                val enhancedChef = ChefSkillCalculator.applyAllSkillsV2(
                                                    chef, ultimateSkills, equip, skills, chefInteractions.getOrNull(chefIndex), gameData
                                                )
                                                val rank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)

                                                if (rank >= 4) {
                                                    // 达到神级时显示菜谱技法需求
                                                    val skillText = getRecipeSkillText(recipe)
                                                    if (skillText.isNotEmpty()) {
                                                        Text(
                                                            text = skillText,
                                                            fontSize = 11.sp,
                                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                                        )
                                                    }
                                                } else {
                                                    // 未达到神级时显示技法差值，支持分段颜色显示
                                                    val (_, skillGaps) = getSkillGapText(enhancedChef, recipe)
                                                    
                                                    if (skillGaps.isNotEmpty()) {
                                                        Row {
                                                            skillGaps.forEachIndexed { index, (skillText, isNegative) ->
                                                                if (index > 0) {
                                                                    Text(
                                                                        text = " ",
                                                                        fontSize = 11.sp,
                                                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                                                    )
                                                                }
                                                                Text(
                                                                    text = skillText,
                                                                    fontSize = 11.sp,
                                                                    color = if (isNegative) Color.Red else MaterialTheme.colorScheme.onSurfaceVariant
                                                                )
                                                            }
                                                        }
                                                    }
                                                }
                                            } else {
                                                // 没有厨师时显示菜谱技法需求
                                                val skillText = getRecipeSkillText(recipe)
                                                if (skillText.isNotEmpty()) {
                                                    Text(
                                                        text = skillText,
                                                        fontSize = 11.sp,
                                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                                    )
                                                }
                                            }
                                }

                                        // 第二行：来源、品级和拥有状态
                                        Row(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(top = 4.dp),
                                            horizontalArrangement = Arrangement.SpaceBetween,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            // 来源
                                            Text(
                                                text = recipe.origin.replace("<br>", "、"),
                                                fontSize = 11.sp,
                                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                modifier = Modifier.weight(1f)
                                            )

                                            // 品级显示（如果有选中的厨师）
                                            val chefIndex = selectedRecipeSlotIndex / 3 // 计算对应的厨师索引
                                            val chef = selectedChefs.getOrNull(chefIndex)
                                            val equip = selectedEquips.getOrNull(chefIndex)

                                            if (chef != null) {
                                                // 应用技法加成（包含厨师间技法影响）
                                                val enhancedChef = ChefSkillCalculator.applyAllSkillsV2(
                                                    chef, ultimateSkills, equip, skills, chefInteractions.getOrNull(chefIndex), gameData
                                                )

                                                val rank = RecipeRankCalculator.calculateRecipeRank(enhancedChef, recipe)

                                                // 显示品级
                                                val rankText = RecipeRankCalculator.getRankShortText(rank)
                                                val rankColor = RecipeRankCalculator.getRankColor(rank)

                                                Text(
                                                        text = rankText,
                                                        fontSize = 10.sp,
                                                        color = Color(rankColor),
                                                        fontWeight = FontWeight.Bold,
                                                        modifier = Modifier.padding(horizontal = 8.dp)
                                                    )
                                            }

                                            // 拥有状态
                                            Text(
                                                text = if (recipe.got) "已拥有" else "未拥有",
                                                fontSize = 10.sp,
                                                color = if (recipe.got)
                                                    MaterialTheme.colorScheme.primary
                                                else
                                                    Color.Red,
                                                modifier = Modifier.padding(start = 8.dp)
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            Row {
                if (searchText.isNotEmpty()) {
                    TextButton(onClick = { searchText = "" }) {
                        Text("清空搜索")
                    }
                }
                TextButton(onClick = {
                    onClearCurrentRecipe() // 只清空当前选择框的菜谱数据
                    onDismiss() // 关闭对话框
                }) {
                    Text("清空当前")
                }
                TextButton(onClick = onDismiss) {
                    Text("关闭")
                }
            }
        }
    )
}

/**
 * 厨师查询对话框
 */
@Composable
private fun ChefQueryDialog(
    chefs: List<Chef>,
    ultimateSkills: UltimateSkillsState,
    onChefSelected: (Chef) -> Unit,
    onDismiss: () -> Unit
) {
    var searchText by remember { mutableStateOf("") }

    // 过滤厨师列表：只显示已拥有且未修炼的厨师
    val filteredChefs = remember(chefs, searchText) {
        chefs.filter { chef ->
            chef.got && !chef.ult && // 已拥有且未修炼
            (searchText.isEmpty() ||
             chef.name.contains(searchText, ignoreCase = true) ||
             chef.origin.contains(searchText, ignoreCase = true))
        }.sortedWith { chef1, chef2 ->
            // 按厨师ID降序排序（ID越大越靠前）
            val id1 = chef1.chefId.toIntOrNull() ?: 0
            val id2 = chef2.chefId.toIntOrNull() ?: 0
            id2.compareTo(id1)
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text("查询厨师")
        },
        text = {
            Column {
                // 搜索框
                OutlinedTextField(
                    value = searchText,
                    onValueChange = { searchText = it },
                    label = { Text("查找") },
                    placeholder = { Text("输入厨师名称或来源") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "搜索"
                        )
                    },
                    trailingIcon = {
                        if (searchText.isNotEmpty()) {
                            IconButton(onClick = { searchText = "" }) {
                                Icon(
                                    imageVector = Icons.Default.Clear,
                                    contentDescription = "清空"
                                )
                            }
                        }
                    }
                )

                Spacer(modifier = Modifier.height(8.dp))

                // 厨师列表
                LazyColumn(
                    modifier = Modifier.height(400.dp)
                ) {
                    if (filteredChefs.isEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = if (searchText.isEmpty()) "没有厨师" else "没有找到",
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    } else {
                        items(filteredChefs) { chef ->
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 2.dp)
                                    .clickable { onChefSelected(chef) },
                                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
                            ) {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(12.dp),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Column(modifier = Modifier.weight(1f)) {
                                        Text(
                                            text = chef.name,
                                            fontSize = 14.sp,
                                            fontWeight = FontWeight.Medium
                                        )
                                        Text(
                                            text = ChefSkillCalculator.getEnhancedSkillText(chef, ultimateSkills),
                                            fontSize = 11.sp,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                    
                                    Column(
                                        horizontalAlignment = Alignment.End
                                    ) {
                                        Text(
                                            text = if (chef.ult) "已修炼" else "未修炼",
                                            fontSize = 10.sp,
                                            color = if (chef.ult)
                                                MaterialTheme.colorScheme.primary
                                            else
                                                Color.Red
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            Row {
                if (searchText.isNotEmpty()) {
                    TextButton(onClick = { searchText = "" }) {
                        Text("清空")
                    }
                }
                TextButton(onClick = onDismiss) {
                    Text("关闭")
                }
            }
        }
    )
}





/**
 * 获取厨师修炼技能描述
 */
private fun getChefSkillDescription(chef: Chef, skills: List<Skill>): String {
    if (!chef.hasUltimateSkill()) return "无修炼技能"
    val descs = chef.getAllUltimateSkills().mapNotNull { sid ->
        skills.find { it.skillId == sid }?.desc
    }
    return if (descs.isEmpty()) "无修炼技能" else descs.joinToString("\n")
}

/**
 * 统一的技法光环厨师筛选逻辑
 * 只显示技法光环厨师，排除售价光环厨师
 */
private fun isAuraChef(chef: Chef, skills: List<Skill>): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    // 获取厨师的所有修炼技能
    val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
        skills.find { it.skillId == skillId }
    }
    
    // 检查是否有符合条件的技法光环技能
    return ultimateSkills.any { skill ->
        skill.effect?.any { effect ->
            // 条件1：condition必须是"Partial"或"Next"
            val conditionMatch = effect.condition == "Partial" || effect.condition == "Next"
            
            // 条件2：type必须是技法类型
            val typeMatch = effect.type in listOf("Bake", "Steam", "Boil", "Fry", "Knife", "Stirfry")
            
            // 条件3：value必须大于0
            val valueMatch = (effect.value ?: 0) > 0
            
            conditionMatch && typeMatch && valueMatch
        } ?: false
    }
}

/**
 * 获取厨具技能描述
 */
private fun getEquipSkillDescription(equip: Equip, skills: List<Skill>): String {
    if (equip.skill.isEmpty()) return ""

    val skillDescriptions = equip.skill.mapNotNull { skillId ->
        skills.find { it.skillId == skillId }?.desc
    }

    return skillDescriptions.joinToString(" ")
}

/**
 * 获取菜谱技法文本
 */
private fun getRecipeSkillText(recipe: Recipe): String {
    val skills = mutableListOf<String>()

    if (recipe.stirfry > 0) skills.add("炒${recipe.stirfry}")
    if (recipe.boil > 0) skills.add("煮${recipe.boil}")
    if (recipe.knife > 0) skills.add("切${recipe.knife}")
    if (recipe.fry > 0) skills.add("炸${recipe.fry}")
    if (recipe.bake > 0) skills.add("烤${recipe.bake}")
    if (recipe.steam > 0) skills.add("蒸${recipe.steam}")

    return skills.joinToString(" ")
}

/**
 * 获取技法差值文本（用于显示达到神级所需的技法差值）
 * @param chef 增强后的厨师
 * @param recipe 菜谱
 * @return 包含差值信息的显示文本和颜色信息
 */
private fun getSkillGapText(chef: Chef, recipe: Recipe): Pair<String, List<Pair<String, Boolean>>> {
    // 计算厨师当前技法值与神级要求（4倍菜谱需求）的差值
    val gaps = mutableListOf<Pair<String, Boolean>>() // Boolean表示是否为负值（红色显示）
    
    if (recipe.stirfry > 0) {
        val godTierRequirement = recipe.stirfry * 4 // 神级需要4倍菜谱需求
        val gap = chef.stirfry - godTierRequirement
        if (gap < 0) {
            gaps.add("炒${gap}" to true) // 负值，红色显示
        } else {
            gaps.add("炒${recipe.stirfry}" to false) // 技法充足时显示菜谱基础需求
        }
    }
    
    if (recipe.boil > 0) {
        val godTierRequirement = recipe.boil * 4
        val gap = chef.boil - godTierRequirement
        if (gap < 0) {
            gaps.add("煮${gap}" to true)
        } else {
            gaps.add("煮${recipe.boil}" to false)
        }
    }
    
    if (recipe.knife > 0) {
        val godTierRequirement = recipe.knife * 4
        val gap = chef.knife - godTierRequirement
        if (gap < 0) {
            gaps.add("切${gap}" to true)
        } else {
            gaps.add("切${recipe.knife}" to false)
        }
    }
    
    if (recipe.fry > 0) {
        val godTierRequirement = recipe.fry * 4
        val gap = chef.fry - godTierRequirement
        if (gap < 0) {
            gaps.add("炸${gap}" to true)
        } else {
            gaps.add("炸${recipe.fry}" to false)
        }
    }
    
    if (recipe.bake > 0) {
        val godTierRequirement = recipe.bake * 4
        val gap = chef.bake - godTierRequirement
        if (gap < 0) {
            gaps.add("烤${gap}" to true)
        } else {
            gaps.add("烤${recipe.bake}" to false)
        }
    }
    
    if (recipe.steam > 0) {
        val godTierRequirement = recipe.steam * 4
        val gap = chef.steam - godTierRequirement
        if (gap < 0) {
            gaps.add("蒸${gap}" to true)
        } else {
            gaps.add("蒸${recipe.steam}" to false)
        }
    }
    
    val displayText = gaps.map { it.first }.joinToString(" ")
    return displayText to gaps
}

/**
 * 厨具拥有状态
 */
data class EquipOwnershipStatus(
    val text: String,
    val color: androidx.compose.ui.graphics.Color
)

/**
 * 获取厨具拥有状态
 */
private fun getEquipOwnershipStatus(equip: Equip, allRecipes: List<Recipe>): EquipOwnershipStatus {
    // 拆分厨具的所有来源
    val equipOrigins = equip.origin.replace("<br>", "、").split("、").map { it.trim() }
    
    // 检查是否包含奖池来源
    val hasPoolOrigin = equipOrigins.any { origin ->
        origin.contains("新手奖池") || 
        origin.contains("中级奖池") || 
        origin.contains("高级奖池") || 
        origin.contains("碧池")
    }
    
    if (hasPoolOrigin) {
        return EquipOwnershipStatus(
            text = "已拥有",
            color = androidx.compose.ui.graphics.Color(0xFF1976D2) // 蓝色，与厨具技法一致
        )
    }

    // 检查是否包含默认可能拥有的来源
    val hasDefaultPossibleOrigin = equipOrigins.any { origin ->
        origin.contains("实验室") || origin.contains("厨神")
    }
    
    // 检查是否有已获得的菜谱来源包含厨具任一来源（需要5个及以上）
    val hasMatchingRecipeOrigin = equipOrigins.any { equipOrigin ->
        val matchingRecipeCount = allRecipes.count { recipe ->
            recipe.got && recipe.origin.contains(equipOrigin)
        }
        matchingRecipeCount >= 5
    }

    return if (hasDefaultPossibleOrigin || hasMatchingRecipeOrigin) {
        EquipOwnershipStatus(
            text = "可能已有",
            color = androidx.compose.ui.graphics.Color(0xFFFFC107) // 黄色
        )
    } else {
        EquipOwnershipStatus(
            text = "未拥有",
            color = androidx.compose.ui.graphics.Color(0xFFF44336) // 红色
        )
    }
}

/**
 * 检查厨具是否有技法加成
 */
private fun hasSkillBonus(equip: Equip, skills: List<Skill>): Boolean {
    if (equip.skill.isEmpty()) return false
    
    return equip.skill.any { skillId ->
        val skill = skills.find { it.skillId == skillId }
        skill?.desc?.contains("技法") == true
    }
}

/**
 * 检查菜谱是否包含指定技法
 */
private fun hasRequiredSkill(recipe: Recipe, skillType: String): Boolean {
    return when (skillType.lowercase()) {
        "knife" -> recipe.knife > 0
        "stirfry" -> recipe.stirfry > 0
        "boil" -> recipe.boil > 0
        "fry" -> recipe.fry > 0
        "bake" -> recipe.bake > 0
        "steam" -> recipe.steam > 0
        else -> false
    }
}

/**
 * 根据神差值比较两个菜谱的排序
 * 排序规则：
 * 1. 优先展示只有单技法神差值的菜谱，按照神差值由低到高排序
 * 2. 多技法神差值的菜谱放在当前品级最后展示，按照每个菜谱神差值最低的那个技法升序排序
 * 3. 最后才按照时间排序
 */
private fun compareByGodTierGaps(chef: Chef, recipe1: Recipe, recipe2: Recipe): Int {
    val gaps1 = calculateRecipeGodTierGaps(chef, recipe1)
    val gaps2 = calculateRecipeGodTierGaps(chef, recipe2)
    
    // 检查是否为单技法神差值
    val isSingleGap1 = gaps1.size == 1
    val isSingleGap2 = gaps2.size == 1
    
    return when {
        // 如果一个是单技法，另一个是多技法，优先单技法
        isSingleGap1 && !isSingleGap2 -> -1
        !isSingleGap1 && isSingleGap2 -> 1
        
        // 如果都是单技法神差值，按神差值由低到高排序
        isSingleGap1 && isSingleGap2 -> {
            val gap1 = gaps1.values.first()
            val gap2 = gaps2.values.first()
            val gapComparison = gap1.compareTo(gap2)
            if (gapComparison != 0) {
                gapComparison
            } else {
                recipe1.time.compareTo(recipe2.time) // 神差值相同时按时间排序
            }
        }
        
        // 如果都是多技法神差值，按每个菜谱神差值最低的那个技法升序排序
        !isSingleGap1 && !isSingleGap2 -> {
            val minGap1 = gaps1.values.minOrNull() ?: Int.MAX_VALUE
            val minGap2 = gaps2.values.minOrNull() ?: Int.MAX_VALUE
            val minGapComparison = minGap1.compareTo(minGap2)
            if (minGapComparison != 0) {
                minGapComparison
            } else {
                recipe1.time.compareTo(recipe2.time) // 最小神差值相同时按时间排序
            }
        }
        
        // 其他情况按时间排序
        else -> recipe1.time.compareTo(recipe2.time)
    }
}

/**
 * 计算菜谱达到神级所需的技法差值
 */
private fun calculateRecipeGodTierGaps(chef: Chef, recipe: Recipe): Map<String, Int> {
    val gaps = mutableMapOf<String, Int>()
    
    // 计算各个技法的差值，返回中文技法名称
    if (recipe.stirfry > 0) {
        val stirfryRequirement = recipe.stirfry * 4
        val deficit = stirfryRequirement - chef.stirfry
        if (deficit > 0) gaps["炒"] = deficit
    }
    if (recipe.boil > 0) {
        val boilRequirement = recipe.boil * 4
        val deficit = boilRequirement - chef.boil
        if (deficit > 0) gaps["煮"] = deficit
    }
    if (recipe.knife > 0) {
        val knifeRequirement = recipe.knife * 4
        val deficit = knifeRequirement - chef.knife
        if (deficit > 0) gaps["切"] = deficit
    }
    if (recipe.fry > 0) {
        val fryRequirement = recipe.fry * 4
        val deficit = fryRequirement - chef.fry
        if (deficit > 0) gaps["炸"] = deficit
    }
    if (recipe.bake > 0) {
        val bakeRequirement = recipe.bake * 4
        val deficit = bakeRequirement - chef.bake
        if (deficit > 0) gaps["烤"] = deficit
    }
    if (recipe.steam > 0) {
        val steamRequirement = recipe.steam * 4
        val deficit = steamRequirement - chef.steam
        if (deficit > 0) gaps["蒸"] = deficit
    }
    
    return gaps
}

/**
 * 设置对话框
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SettingsDialog(
    gameData: GameData?,
    personalData: PersonalData?,
    onDismiss: () -> Unit
) {
    val context = LocalContext.current
    val settingsStorage = remember { SettingsStorage(context) }
    val personalDataManager = remember { PersonalDataManager(context) }

    var searchText by remember { mutableStateOf("") }
    var isDropdownExpanded by remember { mutableStateOf(false) }
        val interactionSource = remember { MutableInteractionSource() }

    // 获取已拥有且已修炼的光环厨师名称集合（同时满足"查询已有"和"查询已修炼"逻辑）
    val ownedAndUltimateAuraChefs = remember(gameData) {
        gameData?.let { data ->
            data.chefs.filter { chef ->
                // 调试贝多分状态
                if (chef.name == "贝多分") {
                    
                }
                chef.got && // 已拥有（对应"查询已有"按钮逻辑）
                chef.ult && // 已修炼（对应"查询已修炼"按钮逻辑）
                isAuraChef(chef, data.skills) // 使用统一的光环厨师筛选逻辑
            }.map { it.name }.toSet()
        } ?: emptySet()
    }

    // 动态获取所有光环厨师名称（不依赖缓存）
    val allAuraChefNames = remember(gameData) {
        if (gameData != null) {
            gameData.chefs.filter { chef ->
                isAuraChef(chef, gameData.skills)
            }.map { it.name }.toSet()
        } else {
            emptySet()
        }
    }



    // 使用Set来跟踪选中的厨师 - 每次打开对话框时重新判断当前用户的光环厨师状态
    var selectedChefNames by remember(allAuraChefNames, personalData) {
        println("DEBUG: 光环厨师选择对话框初始化开始")
        
        val currentGameData = gameData
        val currentPersonalData = personalData
        
        // 重新计算当前用户应该启用的光环厨师（已拥有且已修炼）
        val currentUserEnabledAuraChefs = if (currentGameData != null && currentPersonalData != null) {
            currentGameData.chefs.filter { chef ->
                chef.got && chef.ult && isAuraChef(chef, currentGameData.skills)
            }.map { it.name }.toSet()
        } else {
            emptySet()
        }
        println("DEBUG: 对话框中计算的当前用户光环厨师: ${currentUserEnabledAuraChefs.joinToString(", ")}")
        
        // 获取当前保存的选择
        val savedSelection = settingsStorage.getSelectedAuraChefs()
        println("DEBUG: 对话框中获取的保存选择: ${savedSelection.joinToString(", ")}")
        
        // 每次打开对话框都使用最新的用户状态，确保与用户当前的拥有和修炼状态同步
        val initialSelection = if (currentUserEnabledAuraChefs.isNotEmpty()) {
            // 优先使用当前用户实际的光环厨师状态
            if (savedSelection != currentUserEnabledAuraChefs) {
                println("DEBUG: 检测到光环厨师状态变化，更新选择")
                settingsStorage.saveSelectedAuraChefs(currentUserEnabledAuraChefs)
                personalDataManager.saveUserAuraChefs(currentUserEnabledAuraChefs)
            }
            currentUserEnabledAuraChefs.intersect(allAuraChefNames)
        } else if (savedSelection.isNotEmpty()) {
            // 如果当前没有符合条件的光环厨师，但有保存的选择，使用保存的选择
            println("DEBUG: 当前无符合条件的光环厨师，使用保存的选择")
            savedSelection.intersect(allAuraChefNames)
        } else {
            // 都为空的情况
            println("DEBUG: 无光环厨师数据，使用空选择")
            emptySet()
        }
        
        println("DEBUG: 对话框最终初始化选择: ${initialSelection.joinToString(", ")}")
        mutableStateOf(initialSelection)
    }
    
    // 在对话框打开时重新保存当前选择状态，确保与最新的用户数据同步
    LaunchedEffect(selectedChefNames, allAuraChefNames, personalData) {
        val currentGameData = gameData
        val currentPersonalData = personalData
        
        if (selectedChefNames.isNotEmpty() && currentGameData != null && currentPersonalData != null) {
            settingsStorage.saveSelectedAuraChefs(selectedChefNames)
            personalDataManager.saveUserAuraChefs(selectedChefNames)
        }
    }

    // 监听输入框点击事件
    LaunchedEffect(interactionSource) {
        interactionSource.interactions.collect { interaction ->
            when (interaction) {
                is PressInteraction.Press -> {
                    isDropdownExpanded = true
                }
            }
        }
    }

    // 将厨师按状态分组 - 使用持久化的光环厨师名称
    val groupedChefSkills = remember(gameData, searchText, allAuraChefNames) {
        gameData?.let { data ->
            // 从持久化的光环厨师名称中获取厨师信息
            val allAuraChefs = allAuraChefNames.mapNotNull { chefName ->
                val chef = data.chefs.find { it.name == chefName }
                if (chef != null) {
                    // 查找对应的技能描述
                    val descs = chef.getAllUltimateSkills().mapNotNull { sid ->
                        data.skills.find { it.skillId == sid }?.desc
                    }
                    if (descs.isNotEmpty()) {
                        ChefSkillDataWithStatus(chef.name, descs.joinToString("；"), chef.got, chef.ult)
                    } else {
                        null
                    }
                } else {
                    null
                }
            }.sortedWith { chefSkill1, chefSkill2 ->
                // 按厨师ID降序排序（ID越大越靠前）
                // 需要通过厨师名称找回对应的厨师对象来获取ID
                val chef1 = data.chefs.find { it.name == chefSkill1.name }
                val chef2 = data.chefs.find { it.name == chefSkill2.name }
                val id1 = chef1?.chefId?.toIntOrNull() ?: 0
                val id2 = chef2?.chefId?.toIntOrNull() ?: 0
                id2.compareTo(id1)
            }

            // 应用搜索过滤 - 支持厨师名称和修炼技能搜索
            val filteredChefs = if (searchText.isEmpty()) {
                allAuraChefs
            } else {
                allAuraChefs.filter { chefSkill ->
                    // 搜索厨师名称
                    val nameMatches = chefSkill.name.contains(searchText, ignoreCase = true)
                    // 搜索修炼技能描述
                    val skillMatches = chefSkill.description.contains(searchText, ignoreCase = true)
                    // 搜索技能关键词（如：炒技、全技法、场上所有厨师等）
                    val keywordMatches = chefSkill.description.contains(searchText, ignoreCase = true)

                    nameMatches || skillMatches || keywordMatches
                }
            }

            // 按状态分组
            val ownedAndUltimate = filteredChefs.filter { it.isOwned && it.isUltimate }
            val ownedNotUltimate = filteredChefs.filter { it.isOwned && !it.isUltimate }
            val notOwned = filteredChefs.filter { !it.isOwned }

            GroupedChefSkills(ownedAndUltimate, ownedNotUltimate, notOwned)
        } ?: GroupedChefSkills(emptyList(), emptyList(), emptyList())
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Settings,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary
                )
            Text("设置")
            }
        },
        text = {
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 800.dp), // 设置最大高度，超出时可滚动
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // 描述文字
                item {
                    Text(
                        text = "配置可用光环厨，使用时会生效选中的光环技能",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                }
                
                // 选择光环厨师下拉框
                item {
                    OutlinedTextField(
                        value = searchText,
                        onValueChange = { query ->
                            searchText = query
                            isDropdownExpanded = true
                        },
                        label = {
                            Text(
                                "选择光环厨师",
                                fontSize = 12.sp
                            )
                        },
                        placeholder = {
                            Text(
                                "输入厨师名称或修炼技能",
                                fontSize = 11.sp
                            )
                        },
                        leadingIcon = {
                            Icon(
                                imageVector = Icons.Default.Person,
                                contentDescription = "厨师"
                            )
                        },
                        textStyle = LocalTextStyle.current.copy(fontSize = 12.sp),
                        trailingIcon = {
                            Row {
                                if (searchText.isNotEmpty()) {
                                    IconButton(
                                        onClick = {
                                            searchText = ""
                                            isDropdownExpanded = false
                                        }
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Clear,
                                            contentDescription = "清除"
                                        )
                                    }
                                }

                                // 展开/收起按钮
                                IconButton(
                                    onClick = {
                                        isDropdownExpanded = !isDropdownExpanded
                                    }
                                ) {
                                    Icon(
                                        imageVector = if (isDropdownExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                        contentDescription = if (isDropdownExpanded) "收起" else "展开"
                                    )
                                }
                            }
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        interactionSource = interactionSource
                    )
                }

                // 只有在展开时才显示厨师列表
                if (isDropdownExpanded) {
                    // 全选/清空按钮
                    item {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(2.dp)
                        ) {
                            Button(
                                onClick = {
                                    val defaultSelection = ownedAndUltimateAuraChefs.intersect(allAuraChefNames)
                                    selectedChefNames = defaultSelection
                                    settingsStorage.saveSelectedAuraChefs(defaultSelection)
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                shape = RoundedCornerShape(6.dp),
                                contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = MaterialTheme.colorScheme.surfaceVariant,
                                    contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            ) {
                                Text(
                                    text = "重置",
                                    fontSize = 12.sp
                                )
                            }

                            Button(
                                onClick = {
                                    selectedChefNames = allAuraChefNames
                                    settingsStorage.saveSelectedAuraChefs(allAuraChefNames)
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                shape = RoundedCornerShape(6.dp),
                                contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = MaterialTheme.colorScheme.surfaceVariant,
                                    contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            ) {
                                Text(
                                    text = "全选",
                                    fontSize = 12.sp
                                )
                            }

                            Button(
                                onClick = {
                                    selectedChefNames = emptySet()
                                    settingsStorage.saveSelectedAuraChefs(emptySet())
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                shape = RoundedCornerShape(6.dp),
                                contentPadding = PaddingValues(horizontal = 4.dp, vertical = 4.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = MaterialTheme.colorScheme.surfaceVariant,
                                    contentColor = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            ) {
                                Text(
                                    text = "清空",
                                    fontSize = 12.sp
                                )
                            }
                        }
                    }

                    // 厨师列表
                    item {
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(400.dp), // 使用固定高度替代weight
                            colors = getChefBoxCompatibleCardColors()
                        ) {
                            LazyColumn(
                                modifier = Modifier.padding(4.dp),
                                verticalArrangement = Arrangement.spacedBy(2.dp)
                            ) {
                                // 第一段：已拥有且已修炼的厨师
                                if (groupedChefSkills.ownedAndUltimate.isNotEmpty()) {
                                    item {
                                        SectionHeader("已拥有且已修炼")
                                    }
                                    items(groupedChefSkills.ownedAndUltimate) { chefSkill ->
                                        ChefSkillItemWithStatus(
                                            chefSkill = chefSkill,
                                            isSelected = selectedChefNames.contains(chefSkill.name),
                                            onCheckedChange = { isChecked ->
                                                val newSelection = if (isChecked) {
                                                    selectedChefNames + chefSkill.name
                                                } else {
                                                    selectedChefNames - chefSkill.name
                                                }
                                                selectedChefNames = newSelection
                                                settingsStorage.saveSelectedAuraChefs(newSelection)
                                            }
                                        )
                                    }
                                }

                                // 第二段：已拥有未修炼的厨师
                                if (groupedChefSkills.ownedNotUltimate.isNotEmpty()) {
                                    if (groupedChefSkills.ownedAndUltimate.isNotEmpty()) {
                                        item {
                                            SectionDivider()
                                        }
                                    }
                                    item {
                                        SectionHeader("已拥有未修炼")
                                    }
                                    items(groupedChefSkills.ownedNotUltimate) { chefSkill ->
                                        ChefSkillItemWithStatus(
                                            chefSkill = chefSkill,
                                            isSelected = selectedChefNames.contains(chefSkill.name),
                                            onCheckedChange = { isChecked ->
                                                val newSelection = if (isChecked) {
                                                    selectedChefNames + chefSkill.name
                                                } else {
                                                    selectedChefNames - chefSkill.name
                                                }
                                                selectedChefNames = newSelection
                                                settingsStorage.saveSelectedAuraChefs(newSelection)
                                            }
                                        )
                                    }
                                }

                                // 第三段：未拥有的厨师
                                if (groupedChefSkills.notOwned.isNotEmpty()) {
                                    if (groupedChefSkills.ownedAndUltimate.isNotEmpty() || groupedChefSkills.ownedNotUltimate.isNotEmpty()) {
                                        item {
                                            SectionDivider()
                                        }
                                    }
                                    item {
                                        SectionHeader("未拥有")
                                    }
                                    items(groupedChefSkills.notOwned) { chefSkill ->
                                        ChefSkillItemWithStatus(
                                            chefSkill = chefSkill,
                                            isSelected = selectedChefNames.contains(chefSkill.name),
                                            onCheckedChange = { isChecked ->
                                                val newSelection = if (isChecked) {
                                                    selectedChefNames + chefSkill.name
                                                } else {
                                                    selectedChefNames - chefSkill.name
                                                }
                                                selectedChefNames = newSelection
                                                settingsStorage.saveSelectedAuraChefs(newSelection)
                                            }
                                        )
                                    }
                                }
                            }
                        }
                    }
                }

                // 一键计算配置区域
                item {
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 16.dp), // 调整间距
                        colors = CardDefaults.cardColors(
                            containerColor = getDarkGreyBackgroundColor()
                        )
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(12.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Text(
                                text = "一键查询配置",
                                fontSize = 12.sp,
                                fontWeight = FontWeight.Bold,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            
                            // 是否使用强力厨具开关
                            var usePowerfulEquips by remember { mutableStateOf(settingsStorage.getUsePowerfulEquips()) }
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = "使用强力厨具（加成100以上厨具）",
                                    fontSize = 11.sp,
                                    color = MaterialTheme.colorScheme.onSurface
                                )
                                Switch(
                                    checked = usePowerfulEquips,
                                    onCheckedChange = { checked ->
                                        usePowerfulEquips = checked
                                        settingsStorage.saveUsePowerfulEquips(checked)
                                    },
                                    colors = SwitchDefaults.colors(
                                        checkedThumbColor = MaterialTheme.colorScheme.primary,
                                        checkedTrackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                                    )
                                )
                            }
                            
                            // 是否使用未拥有菜谱开关
                            var useUnownedRecipes by remember { mutableStateOf(settingsStorage.getUseUnownedRecipes()) }
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = "使用未拥有菜谱",
                                    fontSize = 11.sp,
                                    color = MaterialTheme.colorScheme.onSurface
                                )
                                Switch(
                                    checked = useUnownedRecipes,
                                    onCheckedChange = { checked ->
                                        useUnownedRecipes = checked
                                        settingsStorage.saveUseUnownedRecipes(checked)
                                    },
                                    colors = SwitchDefaults.colors(
                                        checkedThumbColor = MaterialTheme.colorScheme.primary,
                                        checkedTrackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                                    )
                                )
                            }
                            
                            // 是否优先使用时间较短菜谱开关
                            var preferShorterTimeRecipes by remember { mutableStateOf(settingsStorage.getPreferShorterTimeRecipes()) }
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = "优先使用时间较短菜谱",
                                    fontSize = 11.sp,
                                    color = MaterialTheme.colorScheme.onSurface
                                )
                                Switch(
                                    checked = preferShorterTimeRecipes,
                                    onCheckedChange = { checked ->
                                        preferShorterTimeRecipes = checked
                                        settingsStorage.savePreferShorterTimeRecipes(checked)
                                    },
                                    colors = SwitchDefaults.colors(
                                        checkedThumbColor = MaterialTheme.colorScheme.primary,
                                        checkedTrackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                                    )
                                )
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("关闭")
            }
        }
    )
}

/**
 * 厨师技能数据类
 */
data class ChefSkillData(
    val name: String,
    val description: String
)

/**
 * 带状态的厨师技能数据类
 */
data class ChefSkillDataWithStatus(
    val name: String,
    val description: String,
    val isOwned: Boolean,
    val isUltimate: Boolean
)

/**
 * 分组的厨师技能数据
 */
data class GroupedChefSkills(
    val ownedAndUltimate: List<ChefSkillDataWithStatus>,
    val ownedNotUltimate: List<ChefSkillDataWithStatus>,
    val notOwned: List<ChefSkillDataWithStatus>
)



/**
 * 厨师技能列表项
 */
@Composable
private fun ChefSkillItem(
    chefSkill: ChefSkillData,
    isSelected: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .background(
                if (isSelected) Color(0xFFE8F5E8) else Color.Transparent
            )
            .padding(vertical = 4.dp, horizontal = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = chefSkill.name,
            fontSize = 12.sp,
            fontWeight = FontWeight.Medium,
            color = Color(0xFF333333),
            modifier = Modifier.width(60.dp)
        )

        Text(
            text = chefSkill.description,
            fontSize = 10.sp,
            color = Color(0xFF666666),
            modifier = Modifier
                .weight(1f)
                .padding(horizontal = 6.dp)
        )

        Checkbox(
            checked = isSelected,
            onCheckedChange = onCheckedChange,
            colors = CheckboxDefaults.colors(
                checkedColor = Color(0xFF4CAF50),
                uncheckedColor = Color(0xFFCCCCCC)
            ),
            modifier = Modifier.size(20.dp)
        )
    }
}

/**
 * 带状态的厨师技能列表项
 */
@Composable
private fun ChefSkillItemWithStatus(
    chefSkill: ChefSkillDataWithStatus,
    isSelected: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .background(
                when {
                    isSelected -> Color(0xFFE8F5E8)
                    chefSkill.isOwned && chefSkill.isUltimate -> Color(0xFFF0F8FF) // 淡蓝色背景 - 已拥有且已修炼
                    chefSkill.isOwned -> Color(0xFFFFF8DC) // 淡黄色背景 - 已拥有未修炼
                    else -> Color(0xFFF5F5F5) // 淡灰色背景 - 未拥有
                }
            )
            .padding(vertical = 4.dp, horizontal = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = chefSkill.name,
            fontSize = 12.sp,
            fontWeight = FontWeight.Medium,
            color = if (chefSkill.isOwned) Color(0xFF333333) else Color(0xFF999999),
            modifier = Modifier.width(60.dp)
        )

        Text(
            text = chefSkill.description,
            fontSize = 10.sp,
            color = if (chefSkill.isOwned) Color(0xFF666666) else Color(0xFFAAAAAA),
            modifier = Modifier
                .weight(1f)
                .padding(horizontal = 6.dp)
        )

        // 状态指示器
        if (chefSkill.isOwned && chefSkill.isUltimate) {
            Text(
                text = "✓",
                fontSize = 12.sp,
                color = Color(0xFF4CAF50),
                modifier = Modifier.padding(end = 4.dp)
            )
        } else if (chefSkill.isOwned) {
            Text(
                text = "○",
                fontSize = 12.sp,
                color = Color(0xFFFF9800),
                modifier = Modifier.padding(end = 4.dp)
            )
        }

        Checkbox(
            checked = isSelected,
            onCheckedChange = onCheckedChange,
            colors = CheckboxDefaults.colors(
                checkedColor = Color(0xFF4CAF50),
                uncheckedColor = Color(0xFFCCCCCC)
            ),
            modifier = Modifier.size(20.dp)
        )
    }
}

/**
 * 分段标题
 */
@Composable
private fun SectionHeader(title: String) {
    Text(
        text = title,
        fontSize = 14.sp,
        fontWeight = FontWeight.Bold,
        color = MaterialTheme.colorScheme.primary,
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp, horizontal = 4.dp)
    )
}

/**
 * 分段分隔线
 */
@Composable
private fun SectionDivider() {
    HorizontalDivider(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp),
        thickness = 1.dp,
        color = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
    )
}

/**
 * 厨师修炼使用说明弹窗组件
 */
@Composable
private fun RecipeCalculatorUsageGuideDialog(
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "厨师修炼使用说明",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            LazyColumn(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                item {
                    Text(
                        text = "如何使用？",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "1. 点击右上角\"设置\"配置查询条件\n2. 搜索选择未修炼的厨师\n3. 点击\"一键查询\"获得修炼方案",
                        fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }
            
                item {
                    Text(
                        text = "设置说明",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "• 勾选光环厨师使其技法加成在场上生效，默认勾选并生效已有的光环厨师\n• \"使用强力厨具\"开启后，查询时会使用技法加成大于100的厨具进行查询\n• \"使用未拥有菜谱\"开启后，会在已有菜谱无法满足修炼任务要求时自动推荐未拥有菜谱\n• \"优先使用时间较短菜谱\"开启后，查询时会优先使用时间较短的菜谱",
                        fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }

                                
                item {
                    Text(
                        text = "修炼查询建议",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "• 查询会优先推荐新手池厨具及实验室厨具，建议先关闭\"使用强力厨具\"开关，查询方案无法满足修炼任务时再开启\n• \"优先使用时间较短菜谱\"建议开启，但可能因为技法不达标原因使用厨具进行弥补，可根据自身需求调整\n• 查询出的推荐组合总如有大量未拥有菜谱及厨具，可手动调整，根据推荐结果判断是否需要补池",
                        fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("知道了")
            }
        }
    )
}